0

I've discovered a very strange behavior of PHP. This code:

   class Foo
{
    const CONSTANT = 'SomeValue';
}

class Bar
{
    public $tmp;

    function __construct()
    {
        $this->tmp = new Foo;
    }
}

$object = new Bar;
echo $object->tmp::CONSTANT;

Gives a parse error:

Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM), expecting ',' or ';' in E:\OpenServer\domains\mvc.local\test.php on line 18

What a hell is that? Why it works only if I introduce an intermediate variable:

$interm = $object->tmp;
echo $interm::CONSTANT

I really don't need any additional variables.

PHP 5.6.3

Audiophile
  • 970
  • 2
  • 8
  • 20

1 Answers1

0

You can access the class constant via the class name, not the object.

e.g. echo Foo::CONSTANT;

Mex
  • 1,011
  • 7
  • 16