PHP warning: Call-time pass-by-reference has been deprecated

Remove & from &$this everywhere, it is not needed. In fact, I think you can remove & everywhere in this code – it is not needed at all.

Long explanation

PHP allows to pass variables in two ways: “by value” and “by reference”. First way (“by value”), you can’t modify them, other second way (“by reference”) you can:

     function not_modified($x) { $x = $x+1; }
     function modified(&$x) { $x = $x+1; }

Note the & sign. If I call modified on a variable, it will be modified, if I call not_modified, after it returns the value of the argument will be the same.

Older version of PHP allowed to simulate behavior of modified with not_modified by doing this: not_modified(&$x). This is “call-time pass by reference”. It is deprecated and should never be used.

Additionally, in very ancient PHP versions (read: PHP 4 and before), if you modify objects, you should pass it by reference, thus the use of &$this. This is neither necessary nor recommended anymore, as object are always modified when passed to function, i.e. this works:

   function obj_modified($obj) { $obj->x = $obj->x+1; }

This would modify $obj->x even though it formally is passed “by value”, but what is passed is object handle (like in Java, etc.) and not the copy of the object, as it was in PHP 4.

This means, unless you’re doing something weird, you almost never need to pass object (and thus $this by reference, be it call-time or otherwise). In particular, your code doesn’t need it.

Leave a Comment