DEV Community

hbgl
hbgl

Posted on

Constants are no longer constant in PHP

I really hope that I am not opening a can of worms here because I think I have found something in PHP that I should not have. Something that should not exist: const mutable objects.

Yes, you read that correctly. Since PHP 8.1, any regular old object can be a constant, even mutable ones. Why is this a big deal? Well, because constants used to be constant and never change. This is no longer the case.

Here, have a quick taste:

<?php

class MyClass {
    public int $value = 1;
    public function set(int $value) { $this->value = $value; }
}

const MY_OBJECT = new MyClass();
// Equivalent to:
// define('MY_OBJECT', new MyClass());

echo MY_OBJECT->value . "\n";
MY_OBJECT->set(2);
echo MY_OBJECT->value . "\n";

// Prints:
// 1
// 2
Enter fullscreen mode Exit fullscreen mode

Interesting.

A short history lesson
If you carefully read the documentation for the define() function in PHP, you will come across the following statement about constant values:

In PHP 5, value must be a scalar value (int, float, string, bool, or null). In PHP 7, array values are also accepted.

https://www.php.net/manual/en/function.define.php

Objects were clearly not intended to be constant values. While there was never an official reason given for this restriction, some argued that it was due to objects being inherently mutable.

With the addition of enums in PHP 8.1, it became possible to use enum cases as constant values. A very useful feature, indeed. Although the documentation for define() was never amended, the following code works as expected:

<?php

enum Suit {
    case Clubs;
    case Diamonds;
    case Hearts;
    case Spades;
}

const CLUBS1 = Suit::Clubs;
define('CLUBS2', Suit::Clubs);
Enter fullscreen mode Exit fullscreen mode

This brings us back to the topic at hand: objects.

Enums are classes, and enum cases are objects

The PHP documentation tells us how enums ought to be classified:

The Enum itself is a class, and its possible cases are all single-instance objects of that class. That means Enum cases are valid objects and may be used anywhere an object may be used, including type checks.

https://www.php.net/manual/en/language.enumerations.overview.php

The second sentence is especially interesting. If an enum case can be used anywhere an object can be used, then is the inverse also true? Remember, enum cases can be used as constants. So what about objects?

<?php

class MyClass {
    public $foo = 123;
}

const MY_OBJECT = new MyClass();
Enter fullscreen mode Exit fullscreen mode

In PHP 8.0 and earlier this code would terminate with an error, but starting with 8.1, it runs just fine.

Constant objects are a now thing (for better or worse).

Defining constant objects

We have already seen two ways to create constant objects: the declare() function and the const keyword at the top level. Both are functionally identical.

<?php

const MY_OBJECT1 = new MyClass();
declare('MY_OBJECT2', new MyClass());

Enter fullscreen mode Exit fullscreen mode

Class constants, however, cannot be declared this way.

<?php

class Foo {
    // Fatal error: New expressions are not supported in this context
    public const MY_OBJECT = new MyClass();
}
Enter fullscreen mode Exit fullscreen mode

Declaring a class constant requires a constant expression, which new MyClass() is not. But do you know what is a constant expression? Another constant! Meaning, we can declare object constants on the class level by reusing global constants.

<?php

const GLOBAL_MY_OBJECT = new MyClass();

class Foo {
    public const MY_OBJECT = GLOBAL_MY_OBJECT;
}
Enter fullscreen mode Exit fullscreen mode

Interestingly, there seems to be a difference between const on the top level and const on the class level that is not mentioned in the documentation.

Using constant objects

When it comes to reading access and method calls, constant objects can be used like any regular object.

<?php

class MyClass {
    public $foo = 123;
    public function getFoo() { return $this->foo; }
    public function setFoo($value) { $this->foo = $value; }
}

const MY_OBJECT = new MyClass();

MY_OBJECT->foo;         // Read property.
MY_OBJECT->getFoo();    // Call function.
MY_OBJECT->setFoo(321); // Call mutating function.
Enter fullscreen mode Exit fullscreen mode

Two things that are off limits, though, are assigning to a property (or offset) and creating a reference to a property.

<?php

// Fatal error: Cannot use temporary expression in write context
MY_OBJECT->foo = 456;
MY_OBJECT[0] = 789;
$x = &MY_OBJECT->foo;
Enter fullscreen mode Exit fullscreen mode

This is not a limitation on the mutability of the object itself. As stated earlier, we can mutate the object through method calls. Rather, it is a limitation of the PHP compiler. From the compiler’s point of view, assigning to a property of a constant object is equivalent to assigning to a property of a temporary object.

<?php

// Fatal error: Cannot use temporary expression in write context
(new MyClass())->foo = 1;
Enter fullscreen mode Exit fullscreen mode

To work around this restriction, we can assign the constant to a regular variable or return the constant from a function.

<?php

$myObject = MY_OBJECT;
$myObject->foo = 1;

function getMyObject() { return MY_OBJECT; }
getMyObject()->foo = 2;
Enter fullscreen mode Exit fullscreen mode

The constant() function may also come in handy as it returns any constant by name, thereby circumventing the ‘temporary expression’ problem.

What do we take from it?

My suggestion is: do not use constant objects (enums aside).

They are counter-intuitive (due to their mutability) and also completely unnecessary. Plus, I am pretty sure that constant objects were never an intended feature in the first place. My theory is that they snuck into the language with the introduction of enums.

It would be for the best if constant objects got removed from the language.

The post Constants are no longer constant in PHP appeared first on hbgl.

Top comments (9)

Collapse
 
mcharytoniuk profile image
Mateusz Charytoniuk • Edited

const means a constant reference; you cannot change scalar values without changing a reference to them, but you can keep the same reference to an object and change it's properties. I think it has always been like that, so the title is a bit misleading.

If you want immutable objects, use readonly classes:

readonly class MyClass { ... }
Enter fullscreen mode Exit fullscreen mode

If you want to use 3rd party class and make sure nobody modifies it, wrap it in a readonly class

readonly class MyWrapper 
{
    public function __construct(private OtherClass $otherClass) {} 

    /* ... */
}
Enter fullscreen mode Exit fullscreen mode

Other languages use that approach also (JS for example), it's just a matter of how a language defines it. We still have ways to enforce immutability, I don't see an issue with that.

Collapse
 
hbgl profile image
hbgl

Until PHP 8.1, const really meant "constant data", i.e. deep immutability. The idea of a constant reference did not exist. The keyword const in JS and PHP have always worked differently. In JS, const refers to a variable binding that cannot be rebound to another piece of data. In that sense, const in JS it is more like readonly in PHP.

Collapse
 
mcharytoniuk profile image
Mateusz Charytoniuk

I can't finy any info on const changes, and that would be a significant think, it's not listen in 8.1 changelog either: php.net/releases/8.1/en.php

I think you might be mistaken. Unless you can point me to a changelog that mentions that?

Thread Thread
 
hbgl profile image
hbgl

I believe that const objects were an unintentional side-effect of allowing const enum cases. Therefore it only makes sense that there is no mention in the changelog.

Collapse
 
ravavyr profile image
Ravavyr

Just use define('BOB','somevalue') like anyone who writes PHP would normally do it.

Hell even PHP's documentation says so:
php.net/manual/en/language.constan...

To sum up, use "define()" for global constants in an application and use "const" for in-class-scope constants.

Personally, i'll just use variables for everything because the only "constant" in web dev is that everything changes...eventually.

Collapse
 
romson profile image
Roman

I also didn't encounter a situation yet when using constant objects was a suitable option. But I'd like to point out that from the technical perspective, the mutability of the object should not be confusing when it's used with a constant because objects are reference types. Therefore, the constant does not contain an object, rather it contains a reference to the object and that reference is constant but the internal state of the object can be changed. You still can't assign a new value (a reference to another object) to the constant, so the constant can not be changed.

Collapse
 
hbgl profile image
hbgl • Edited

I believe the distinction between object references and object data is not suitable when we are talking about constants. A constant should refer to deeply immutable data, like π being equal to 3.14. From this perspective, having a constant reference is a bit of a nonsensical concept.

Collapse
 
citronbrick profile image
CitronBrick

When you say "no longer" do you meant that previously in PHP const objects were not mutable ?

Is this a change or a discovery ?

Collapse
 
hbgl profile image
hbgl

Before PHP 8.1, you could not have const objects at all. Only scalars and arrays were allowed which are effectively immutable. Objects are and always have been mutable in PHP.