PHP call_user_func与回调函数的结合使用

957 阅读1分钟
$closureFunc = function(){
    return new RedisDB([
        'host' => '127.0.0.1',
        'port' => 6379
    ]);
};

$closureFunc();

上面代码是一个简单的匿名函数写法

print_r($closureFunc);
$instance = call_user_func($closureFunc);
print_r($instance);

现在打印如上语句,其结果一样的,都是RedisDB对象:

app\components\RedisDB Object
(
    [_di:protected] => 
    [_options:protected] => Array
        (
            [host] => 127.0.0.1
            [port] => 6379
        )

)
app\components\RedisDB Object
(
    [_di:protected] => 
    [_options:protected] => Array
        (
            [host] => 127.0.0.1
            [port] => 6379
        )

)

如果打印print_r($closureFunc);其结果是Closure Object:

Closure Object
(
    [this] => app\modules\student\controllers\IndexController Object
        (
            [modelClass] => app\models\db\XmUsers
            [response] => app\common\base\BaseResponseService Object
                (
                    [format] => json
                    [acceptMimeType] => application/json
                    [acceptParams] => Array
                        (
                        )

                    [formatters] => Array
                        (
                            [html] => Array
                                (
                                    [class] => yii\web\HtmlResponseFormatter
                                )

                            [xml] => Array
                                (
                                    [class] => yii\web\XmlResponseFormatter
                                )

                            [json] => Array
                                (
                                    [class] => yii\web\JsonResponseFormatter
                                )

                            [jsonp] => Array
                                (
                                    [class] => yii\web\JsonResponseFormatter
                                    [useJsonp] => 1
                                )

                        ) 

上面结果我只截取一小部分,确实是Closure对象


也就是说call_user_func参数可以是匿名对象,官方文档有这么一句话:

call_user_func may also be used to call a closure or anonymous function that has been passed into a user-defined function.

大意是:call_user_func还可用于调用已传递到用户定义函数的闭包或匿名函数。


参考:www.php.cn/php-weiziji…

         www.jianshu.com/p/a3dd052aa…