For PHP, all objects are mutable. Since constants should never change at runtime but objects can, object-constants are currently not supported.
In the phpdoc about constants, it is stated that:
When using the const keyword, only scalar data (boolean, integer,
float and string) can be contained in constants prior to PHP 5.6. From
PHP 5.6 onwards, it is possible to define a constant as a scalar
expression, and it is also possible to define an array constant. It is
possible to define constants as a resource, but it should be avoided,
as it can cause unexpected results.
There is an inconsistency with arrays though and no rational is given as to why array constants are allowed. (I would even argue that it was a bad call.) It must be noted that array-constants
are immutable, hence trying to change them results in Fatal error as showcased by this code from php7:
<?php
$aNormalMutableArray = ['key' => 'original'];
$aNormalMutableArray['key'] = 'changed';
echo $aNormalMutableArray['key'];
define(
'IMMUTABLE_ARRAY',
[
'key' => 'original',
]
);
IMMUTABLE_ARRAY['key'] = 'if I am an array, I change; if I am a constant I throw an error';
echo IMMUTABLE_ARRAY['key'];
throwing:
PHP Fatal error: Cannot use temporary expression in write context
in ~/wtf.php on line 12
Why it isn't possible to define object constants with a similar error? One has to ask the power that be.
I recommend staying away from arrays and objects as constants. Rather create an immutable objects or use immutable collections instead.
Since you are looking for a certain syntax, there already is the concept of class constants.
<?php
class MyClass
{
const CONSTANT = 'constant value';
function showConstant() {
echo self::CONSTANT . "\n";
}
}
echo MyClass::CONSTANT . "\n";
$classname = "MyClass";
echo $classname::CONSTANT . "\n"; // As of PHP 5.3.0
$class = new MyClass();
$class->showConstant();
echo $class::CONSTANT."\n"; // As of PHP 5.3.0
It's also possible to define them in interfaces.