Table of contents

Invoke call_user_func_array error: expected to be a reference, value given

PHP Feb 16, 2021 Viewed 13 Comments 0

Issue

Use the call_user_func_array method to call a callback, and pass parameters by reference. The code is as below.

<?php

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

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

I get an error as follow.

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

Solution

The parameter of call_user_func_array also adds the reference mark &.

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

Note: call_user_func can only pass parameters by value, not by reference. As the PHP manual :

Note:

Note that the parameters for call_user_func() are not passed by reference.

Updated Feb 16, 2021