PHP Call a instance method with call_user_func within the same class

前端 未结 3 1440
深忆病人
深忆病人 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:16

    This works for me:

    <?php
    class MyClass
    {
        public function __construct()
        {
            $this->foo('bar');
        }
        public function foo($method)
        {
            return call_user_func(array($this, $method), 'Hello World');
        }
    
        public function bar($message)
        {
            echo $message;
        }
    }
    
    $mc = new MyClass();
    ?>
    

    This gets printed out:

    wraith:Downloads mwilliamson$ php userfunc_test.php 
        Hello World
    
    0 讨论(0)
  • 2020-12-17 09:17

    new MyClass; Should return 'Hello World'...

    A constructor does not return anything.

    0 讨论(0)
  • 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;
         }
    }
    
    0 讨论(0)
提交回复
热议问题