Only Initialize With Short Assignation Coalesce¶
<?php
class x {
private static self $x;
static function getInstance() {
// all good
return self::$x ??= new self();
}
static function getInstance2() {
// Not ok : cannot access before initialisation
return self::$x = self::$x ?? new self();
}
static function getError() {
// Not ok : cannot access before initialisation
if (!self::$x instanceof self) {
self::$x = new self();
}
return self::$x;
}
}
It is not possible to access a property before its initialisation. This is true to both static and normal properties.
While normal properties are initialized at constructor time, static properties might require a check before assignation : in case the property has not been yet assigned, a Fatal error will stop the code execution.
In fact, there is a way : it is the short assignation with coalesce, which will accept to check the NULL value, and only fill it if it is null.
See Also¶
this function never returns [Try me]
PHP Features¶
Last updated: 14 July 2026