call_user_func() expects parameter 1 to be a valid callback

后端 未结 2 592
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 12:34

I\'m just playing around with the call_user_func function in PHP and am getting this error when running this simple code:



        
相关标签:
2条回答
  • 2020-12-10 12:58

    $this->var is evaluating to printHi in your example. However, when you are calling a method of a class, you need to pass the callback as an array where the first element is the object instance and the second element is the function name:

    call_user_func(array($this, $this->var));
    

    Here is the documentation on valid callbacks: http://www.php.net/manual/en/language.types.callable.php

    0 讨论(0)
  • 2020-12-10 13:04

    Alternatively to Omar's answer, you can also make printHi() a class static function, so you then can call it from call_user_func('A::printHi') , like this:

    class A
    {
    
        public $var;
        public static function printHi()
        {
    
            echo "Hello";   
    
        }
    
        public function __construct($string)
        {
            $this->var = $string;   
    
    
        }
    
        public function foo()
        {
    
            call_user_func($this->var); 
    
        }
    
    }
    
    $a = new A('A::printHi');
    $a->foo();
    

    See live example

    0 讨论(0)
提交回复
热议问题