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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13366249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:15:38  来源:igfitidea点击:

call_user_func() expects parameter 1 to be a valid callback

phpdictionary

提问by thed0ctor

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

我只是在玩 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();


?>

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.

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

回答by DiverseAndRemote.com

$this->varis evaluating to printHiin 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:

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

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

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

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

回答by Nelson

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:

除了奥马尔的回答,您还可以创建printHi()一个类静态函数,这样您就可以从 调用它call_user_func('A::printHi'),如下所示:

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

查看现场示例