PHP class constant values

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();
echo $o1::ALPHA . PHP_EOL; // (Output= 0) It works when passing an object

$t1 = new two();
$o2 = $t1->getOne();

echo $o2::ALPHA . PHP_EOL; // (Output= 0) It works when using an object returned from a getter

$t1->printAlphaDirectly(); // PHP Parse error:  syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

$t1->printAlphaTmp(); // (Output= 0) It works when using a tmp var to hold the object

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s