Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access substring of class constant with array index operator

class Foo {
 const BAR = 'Hello';
}

echo Foo::BAR; //Works
echo Foo::BAR[0]; //Parse error: syntax error, unexpected '[', expecting ',' or ';'

I've found a way around this by using substr, but I'm curious to know why this doesn't work as it is.

PHP 5.3.3 by the way.

like image 556
daniel Avatar asked Jan 23 '26 12:01

daniel


1 Answers

I guess that PHP considers class constants like "classic" constants (e.g. created with define()).

Therefore, they are simply replaced by their values at runtime, so Foo::BAR[0] would be interpreted by PHP as 'Hello'[0] which is not a valid syntax ($myVariable[0] being allowed).

like image 86
Frosty Z Avatar answered Jan 26 '26 01:01

Frosty Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!