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

$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…


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值