PHP › OOP
How does late static binding, using the static keyword instead of self, allow inherited static methods to correctly reference the actual calling child class rather than the parent class where the method was originally defined?
AdvancedAnswer
When a static method uses self to reference the current class, that reference always resolves to the class where the method was actually defined, even when called through a child class, whereas using the static keyword instead resolves to whichever specific class was actually used to make the call, a behavior called late static binding, which is essential for patterns like a base class providing a shared static factory method that should correctly return an instance of whichever specific subclass actually called it.
class Model {
public static function create(): static {
return new static();
}
}
class User extends Model {
}
$user = User::create();
echo get_class($user);Real-world example A base Model class provides a shared static create factory method using late static binding, ensuring that calling User::create actually returns a genuine User instance rather than incorrectly always returning a plain Model instance regardless of which specific subclass was called.