Question

Quoting the PHP reference manual which states:

as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error

And yet it seems to work with the following code on PHP 5.5?:

<?php
error_reporting(E_ALL);

class parentClass
{
    function _funcA()
    {
        var_dump($this);
    }
}

class childClass extends parentClass
{
    function funcA()
    {
        call_user_func_array(array(&$this, '_funcA'), array());
    }
}

$test = new childClass();
$test->funcA();

So is the documentation wrong? Or is there some special caveat the documentation isn't mentioning? Why does this work when the documentation implies that it shouldn't?

edit: the fact that $this is an object doesn't seem to matter as the following still results in a fatal error:

<?php
function f($v) { return $v->x++; }
$a = new StdClass();
$a->x = 1;
$b = f(&$a);
var_dump($a, $b);
Was it helpful?

Solution

In your original code you are not passing $this by reference to call_user_func_array, it may look like it, but you are not.

You are passing in an array of a reference and a string, and an empty array.

So you are not passing a reference to the function, you are just passing 2 arrays.

OTHER TIPS

The removed thing is "call-time pass-by-reference", not "Passing by Reference".

You can still pass reference to function, but you need to define function parameter with '&'. When doing on function call, you must not use '&' before '$' of variable, that will cause warning(5.3) or error(5.4).

So, your simple function above will be fixed like this:

<?php
function f(&$v)        // '&' is added here
  { return $v->x++; }
$a = new StdClass();
$a->x = 1;
$b = f($a);            // '&' is removed here
var_dump($a, $b);

And, in your beginning case, is a different question. $this is a pointer to class instance itself, '&$this' will have same value. Object parameter in PHP5 is already pass by reference, you need not add '&' before them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top