PHP Link to `$ this`

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.

+5
source share
1 answer

The value of val ( $this ) is not global, the scope is changing, so it gets ZCAL_STR_COPY .

 case EXTR_OVERWRITE: /* GLOBALS protection */ if (var_exists && ZSTR_LEN(var_name) == sizeof("GLOBALS")-1 && !strcmp(ZSTR_VAL(var_name), "GLOBALS")) { break; } if (var_exists && ZSTR_LEN(var_name) == sizeof("this")-1 && !strcmp(ZSTR_VAL(var_name), "this")) { zend_class_entry *scope = zend_get_executed_scope(); if (scope && ZSTR_LEN(scope->name) != 0) { break; } } ZVAL_STR_COPY(&final_name, var_name); break; 

Thanks for making me peek into the PHP source code for array.c :)

+1
source

Source: https://habr.com/ru/post/1272213/


All Articles