Monday 20 November 2017

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

itemprop="text">


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
href="http://php.net/manual/de/migration70.incompatible.php#migration70.incompatible.variable-handling.indirect"
rel="nofollow noreferrer">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 href="https://wiki.php.net/rfc/uniform_variable_syntax" rel="nofollow noreferrer">PHP
RFC: Uniform Variable Syntax (Status: implemented) - Thanks to href="https://stackoverflow.com/questions/38468161/why-can-i-use-a-string-literal-as-a-class-in-php7/38468719#comment64343727_38468161">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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...