3
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.

1
  • Note that you may be able to do what you need to do like this: $foo = Foo::BAR; $foo = $foo[0]; Commented Jan 1, 2012 at 14:23

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.