PHP Call a instance method with call_user_func within the same class

前端 未结 3 1452
深忆病人
深忆病人 2020-12-17 09:07

I\'m trying to use call_user_func to call a method from another method of the same object, e.g.

class MyClass
{
    public function __construct(         


        
3条回答
  •  自闭症患者
    2020-12-17 09:21

    The code you posted should work just fine. An alternative would be to use "variable functions" like this:

    public function foo($method)
    {
         //safety first - you might not need this if the $method
         //parameter is tightly controlled....
         if (method_exists($this, $method))
         {
             return $this->$method('Hello World');
         }
         else
         {
             //oh dear - handle this situation in whatever way
             //is appropriate
             return null;
         }
    }
    

提交回复
热议问题