PHP Late Static Binding
Late static binding comes from an internal feature of PHP that stores the class named in the last "non-forwarding call". In simpler terms, it allows you to reference the class that was actually called at runtime, rather than the class where the method is defined.
1. The Limitation of self::
Normally, self:: refers to the class in which the code is written (compile-time resolution). This can be problematic when using inheritance.
class Model {
public static function getTableName() {
return 'generic_model';
}
public static function select() {
// self:: refers to Model, even if called from User
echo "SELECT * FROM " . self::getTableName();
}
}
class User extends Model {
public static function getTableName() {
return 'users';
}
}
User::select(); // Outputs: SELECT * FROM generic_model
2. Using static:: (Late Static Binding)
To fix this, PHP 5.3 introduced the static:: keyword. It refers to the class that was initially called at runtime.
class Model {
public static function getTableName() {
return 'generic_model';
}
public static function select() {
// static:: refers to the class that called the method
echo "SELECT * FROM " . static::getTableName();
}
}
class User extends Model {
public static function getTableName() {
return 'users';
}
}
User::select(); // Outputs: SELECT * FROM users
3. self vs static
| Keyword | Resolution Time | Refers To |
|---|---|---|
self:: |
Compile Time | The class where the method is defined. |
static:: |
Runtime | The class that invoked the method. |