Thursday, October 3, 2019

php - Why can I use a string literal as a class in php7?



Consider the following code:



class foo {
static $bar = 'baz';
}
var_dump('foo'::$bar);





It throws an error in PHP5 (as expected):




Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in [...][...] on line 4







But it works without an issue in PHP7 and outputs:



string(3) "baz"





Is that intentional or a bug?


Answer



I think it's because they rewrote stuff regarding evaluation.



like the following is not possible in PHP5 but in PHP 7:



echo (new X)->toString();


Same would go for



echo ('X')::$bar


See Changes to the handling of indirect variables, properties, and methods



This is mainly about the left-to-right evaluation but it also affects the evaluation in general.



More information can be found on PHP RFC: Uniform Variable Syntax (Status: implemented) - Thanks to Nikic:




This RFC proposes the introduction of an internally consistent and
complete variable syntax. To achieve this goal the semantics of some
rarely used variable-variable constructions need to be changed.



No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...