Static scope
Static locals
A static local keeps its value between calls while staying hidden inside the function. The first call sets it up and later calls reuse it.
Counters and memo caches are classic uses that avoid global variables.
function nextId(): int {
static $n = 0;
$n = $n + 1;
return $n;
}
echo nextId();
echo nextId();
Static methods
Static methods belong to the class itself and run without an object. Call them with two colons after the class name.
They suit pure helpers and factories that build objects from simple input.
class Str {
public static function shout(string $s): string {
return strtoupper($s) . "!";
}
}
echo Str::shout("hi");
self vs static
Keyword self always points at the class where the code lives. Keyword static points at the class used in the actual call.
Child classes inherit factories, so static returns the child while self would freeze the parent.
class Base {
public static function make(): static {
return new static();
}
}
class Child extends Base {
}
echo get_class(Child::make());
Singleton sketch
A singleton stores one shared instance in a static property. A static maker builds it once and returns the same object every time.
Use this shape sparingly for registries and configs, since global state makes tests harder.
class Config {
private static ?Config $one = null;
public static function shared(): Config {
if (self::$one === null) {
self::$one = new Config();
}
return self::$one;
}
}
var_dump(Config::shared() === Config::shared());
Next: Union, intersection, DNF types
Автор статьи: Arthur Isaev