user245734 user245734 - 1 year ago 100
PHP Question

Why can't PHP have a constant object?

I have a key-value database table, where I store some settings.

I would like to have these settings in a PHP constant object, since they shouldn't be editable.

In PHP7 we can now do this:

define('MySettings', array(
'title' => 'My title'
// etc

// And call it with
echo MySettings['title'];

And it works great.

But why can't I do:

define('MySettings', (object) array('title' => 'My title'));

So I could call it like this instead:

echo MySettings->title;
// or
echo MySettings::title;

This is only because I think it's quicker and prettier to type it as an object property/constant (
), than as array (

Is there any reason this is not possible?

Answer Source

Constant objects make no sense as objects are mutable by definition. Constants should never change at runtime, objects can.

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 no much rational given as to why array are allowed, I would even argue that it was a bad call. One would expect to be able to modify properties of an array at runtime, yet one also would also expect for changes to constants to fail.

Hence I checked with php7:

$aNormalMutableArray = ['key' => 'original'];
$aNormalMutableArray['key'] = 'changed';
echo $aNormalMutableArray['key'];

        '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'];

and true enough, it throws:

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 for one would stay away from array (and objects) as constants.

Since you are looking for a certain syntax, there already is the concept of class constants.

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();

echo $class::CONSTANT."\n"; // As of PHP 5.3.0

It's also possible to define them in interfaces.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download