Late static binding
self binds early
The self keyword always points at the class where the method is written. It ignores later children of that class.
A child that overrides a static property still sees the parent value through self. The binding happens at write time, not at call time.
class Base {
protected static string $who = "base";
public static function who(): string {
return self::$who;
}
}
static:: binds late
The static keyword keeps the called class until the call runs. The same method can then answer per child.
Call the method on the child and static resolves to the child. Call it on the parent and it resolves to the parent.
class Base {
protected static string $who = "base";
public static function who(): string {
return static::$who;
}
}
class Child extends Base {
protected static string $who = "child";
}
echo Child::who();
forward_static_call note
The forward_static_call function passes late binding along to another callable. A plain call_user_func would drop that context.
Reach for the forward form inside static helpers that hand work to the next method.
class Helper {
public static function who(): string {
return static::class;
}
public static function run(): string {
return forward_static_call([static::class, "who"]);
}
}
Framework pattern
Frameworks use late binding for shared factories. The parent defines make once, and each child gets its own type back.
The static return type promises the child type, and new static builds it. One factory then serves the whole tree.
class Model {
public static function make(): static {
return new static();
}
}
class User extends Model {
}
$user = User::make();
Next: Variance
Автор статьи: Arthur Isaev