call_user_func()期望参数1是有效的回调

the*_*tor 14 php dictionary

我只是在PHP中使用call_user_func函数,并在运行这个简单的代码时遇到此错误:

<?php


class A
{

    public $var;
    private function printHi()
    {

        echo "Hello";   

    }

    public function __construct($string)
    {
        $this->var = $string;   


    }

    public function foo()
    {

        call_user_func($this->var); 

    }

}

$a = new A('printHi');
$a->foo();


?>
Run Code Online (Sandbox Code Playgroud)

我知道如果我在名为printHi的类之外创建一个函数,它工作正常,但我指的是类的print hi并且不确定为什么"this"没有被注册.

Div*_*com 25

$this->var正在评估printHi你的例子.但是,当您调用类的方法时,需要将回调作为数组传递,其中第一个元素是对象实例,第二个元素是函数名称:

call_user_func(array($this, $this->var));
Run Code Online (Sandbox Code Playgroud)

以下是有效回调的文档:http://www.php.net/manual/en/language.types.callable.php