Modify Object Stored in Constant in PHP 8.6

Modify Object Stored in Constant in PHP 8.6

In PHP, a constant can hold an object since PHP 8.1, when the new keyword became available in initializers. Reading a property of such an object was allowed, but writing to it ended with a fatal error.

Since PHP 8.6, properties of an object stored in a constant can be modified:

Settings.php

<?php

class Settings
{
    public bool $debug = false;
    public int $timeout = 10;
}
<?php

require_once 'Settings.php';

const CONFIG = new Settings();

CONFIG->debug = true;

var_dump(CONFIG->debug);
var_dump(CONFIG->timeout);

Before PHP 8.6:

Fatal error: Cannot use temporary expression in write context in main.php on line 7

Since PHP 8.6:

bool(true)
int(10)

The error raised by earlier versions came from the compiler, so the script produced no output at all, not even the lines before the assignment.

Only the properties of the object can be changed. The constant itself remains a constant.

A constant holds a single object, and every use of the constant refers to that same instance. A property changed in one function is therefore visible everywhere else, which makes such a constant behave like global mutable state.

Leave a Comment

Cancel reply

Your email address will not be published.