Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ($obj->key, $obj::key), than as array ($array['key'])

Is there any reason this is not possible?

like image 537
JemoeE Avatar asked Sep 22 '16 14:09

JemoeE


1 Answers

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.

like image 119
k0pernikus Avatar answered Oct 09 '22 21:10

k0pernikus