Noticed today that there are more than one ways to access the constants of a class when using the class name, or when using an object of the class to access the constant or even when using an object of the class as the value of a property of another class. The different ways are shown in the code snippets that follow along with a parse error that is generated when the constant is accessed as part of an object’s property.
class one { const ALPHA = 0; function __construct() {} }
class two { protected $oo1; public function __construct() { $this->oo1 = new one(); } public function getOne() { return $this->oo1; } public function printAlphaDirectly() { echo $this->oo1::ALPHA . PHP_EOL; } public function printAlphaTmp() { $tmp = $this->oo1; echo $tmp::ALPHA . PHP_EOL; } }
echo one::ALPHA . PHP_EOL; // (Output= 0) It works as expected $o1 = new one(); // (Output= 0) It works when passing an object echo $o1::ALPHA . PHP_EOL; $t1 = new two(); $o2 = $t1->getOne(); // (Output= 0) It works when using an object returned from a getter echo $o2::ALPHA . PHP_EOL; // PHP Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) $t1->printAlphaDirectly(); // (Output= 0) It works when using a tmp var to hold the object $t1->printAlphaTmp();
The output of the above echo statements is 0 when the constant value is returned properly but the printAlphaDirectly method produces a T_PAAMAYIM_NEKUDOTAYIM parsing error.
Update: This is tested with PHP version 5.4.4.