How does PHP interpret &$this ? Why is this allowed?
I came to this question with the following problems that look like a bug in PHP 7.1 and 7.2. This happens with the &$this links and the cross-namespace and call_user_func_array . I think &$this rather strange and should not be allowed, but WordPress uses it, for example.
Consider this code:
<?php namespace N { function callNeedRef( $a ) { var_dump( $a ); call_user_func_array( 'needRef', $a ); } } namespace { function needRef( &$r ) { } function callNeedRef( $a ) { var_dump( $a ); call_user_func_array( 'needRef', $a ); } class C { function f() { $a = $this; callNeedRef( array( &$a ) ); // no warning (expected), OK! N\callNeedRef( array( &$a ) ); // no warning (expected), OK! callNeedRef( array( &$this ) ); // no warning (expected), but 7.1,7.2: var_dump prints no '&' N\callNeedRef( array( &$this ) ); // 7.1,7.2: warn and var_dump prints no '&' } } echo "<pre>"; echo phpversion() . PHP_EOL; $o = new C(); $o->f(); }
And his conclusion:
7.2.0RC2 array(1) { [0]=> &object(C)#1 (0) { } } array(1) { [0]=> &object(C)#1 (0) { } } array(1) { [0]=> object(C)#1 (0) { } } array(1) { [0]=> object(C)#1 (0) { } } Warning: Parameter 1 to needRef() expected to be a reference, value given in reftest.php on line 6
As already mentioned in the code, the last two var_dump do not put the object as a reference. And the last call even gives a warning.
source share