self vs static
class Base {
public static function create(): static {
return new static(); // the class it was called on
}
public static function name(): string {
return static::class; // Late Static Binding
}
}
class Child extends Base {}
Child::create(); // returns Child, not Base
Child::name(); // "Child", not "Base"
Where it is used
- Fluent interfaces and Builder patterns that return
static
- ActiveRecord style:
User::find(1) returns User, not the base class
- Static factory methods in class hierarchies