Object support in class constants
| From: | Marc B. | Date: | Sun, 18 Jan 2026 17:55:43 +0000 |
| Subject: | Object support in class constants | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-129783@lists.php.net to get a copy of this message | ||
Hi all,
Somehow I missed that objects can be used in constants `const OBJ = new stdClass();` since PHP 8.1.
As this is allowed for constants, I don't understand why this is not allowed for class constants.
class Test {
public const OBJ = new stdClass(); // Fatal error: New expressions are not supported in this context
}
While this works:
const OBJ = new stdClass();
class Test {
public const OBJ = OBJ; // works
}
Is there are a reason for this limitation especially since "new" expression is valid for argument default values as well?
Thanks,
Marc