call_user_func()期望参数1成为有效的回调 [英] call_user_func() expects parameter 1 to be a valid callback
问题描述
<?php
class A
{
public $ var;
private function printHi()
{
echoHello;
}
public function __construct($ string)
{
$ this-> var = $ string;
}
public function foo()
{
call_user_func($ this-> var);
}
}
$ a = new A('printHi');
$ a-> foo();
?>
我知道如果我在一个名为printHi的类之外做一个函数,它工作正常, m指的是类的打印不知道为什么这个没有被注册。
$ this-> var
在您的示例中评估为 printHi
,但是当您调用需要传递的类的方法时回调作为数组,第一个元素是对象实例,第二个元素是函数名:
call_user_func(array($这个,$ this-> var));
以下是有效回调的文档: http://www.php.net/manual/en/language.types.callable.php
I'm just playing around with the call_user_func function in PHP and am getting this error when running this simple code:
<?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();
?>
I know that if I make a function outside the class called printHi, it works fine, but I'm referring to the class's print hi and not sure why the "this" isn't being registered.
$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 documentation on valid callbacks: http://www.php.net/manual/en/language.types.callable.php
这篇关于call_user_func()期望参数1成为有效的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!