4

I was wondering if there was some way to interpolate class constants in strings without storing them in other variables first. Consider the following code:

class Foo {
  const BAR = 'baz';
}

$foo = new Foo(); // or $foo = 'Foo';

echo "{$foo::BAR}";
// PHP 5.6: Parse error: syntax error, unexpected '}', expecting '('
// PHP 7.*: Parse error: syntax error, unexpected '}', expecting '['
// PHP 8.0: Parse error: syntax error, unexpected token "}", expecting "->" or "?->" or "{" or "["

The error messages seem to indicate that PHP is expecting an array access operator, and sure enough:

class Foo {
  const BAR = 'baz';
}

$foo = new Foo(); // or $foo = 'Foo';

echo "{$foo::BAR[2]}";
// PHP 5.6: Parse error: syntax error, unexpected '[', expecting '('
// PHP 7.*: 'z'
// PHP 8.0: 'z'

Using array access on a string treats it as an array of characters, so this is expected PHP behaviour. If the class constant is set as an array, the full value can be accessed. If the class constant is numeric, it can't be accessed since numerical values don't automatically convert to arrays.

Why does PHP >= 7.0 allow class constants to be accessed as arrays but not as plain strings or numeric values inside a string?

CJ Dennis
  • 4,226
  • 2
  • 40
  • 69
  • why not using just echo $foo::BAR; ? It seems fine. – Nickal Sep 06 '21 at 02:36
  • 1
    @Nic I said the same thing (and deleted my comment). This is a forced example of how to trigger the parse error. It is a good question with a [mcve], I think. – mickmackusa Sep 06 '21 at 03:10

0 Answers0