PHP 使用 call_user_func_array 方法引起:expected to be a reference, value given

Php 2021-02-15 阅读 54 评论 0

问题描述

使用 call_user_func_array 方法调用 callback 方法,而且是将一个变量通过引用传递给函数,代码如下:

<?php

class TestAction
{
    public function getResult(&$data)
    {
        $data[] = "xyz";
    }
}

$test = new TestAction();
$data = ["abc"];
call_user_func_array([$test, "getResult"], [$data]);

最后有一个警告,导致无法运行 callback 方法。

Warning: Parameter 1 to TestAction::callback() expected to be a reference, value given in index.php on line 13

解决方法

call_user_func_array 的参数也加上引用标志 &

call_user_func_array([$test, "callback"], [&$data]);

注:使用call_user_func 方法不能实现引用的传参,只能传递值。参考 官网使用手册

注意:

请注意,传入call_user_func()的参数不能为引用传递。

最后更新 2021-02-15
MIP.watch('startSearch', function (newVal, oldVal) { if(newVal) { var keyword = MIP.getData('keyword'); console.log(keyword); // 替换当前历史记录,新增 MIP.viewer.open('/s/' + keyword, {replace: true}); setTimeout(function () { MIP.setData({startSearch: false}) }, 1000); } }); MIP.watch('goHome', function (newVal, oldVal) { MIP.viewer.open('/', {replace: false}); });