What is Late Static Binding in PHP?
Late static binding is a PHP feature introduced in version 5.3 that
allows you to reference the class that was initially called at runtime
within a static context. This article explains the core concept of late
static binding, demonstrates how it solves the limitations of the
self:: keyword using the static:: keyword, and
provides practical code examples to clarify its usage in object-oriented
programming.
The Problem with self::
In PHP, the self keyword does not follow the rules of
inheritance. Instead, self always resolves to the class in
which the pointer is written. This is known as early binding (or
compile-time binding).
If a parent class has a static method that uses self::,
and a child class extends that parent class and calls the method, PHP
will still reference the parent class, not the child.
Here is an example demonstrating this limitation:
class Model {
protected static $tableName = 'generic_table';
public static function getTableName() {
return self::$tableName;
}
}
class User extends Model {
protected static $tableName = 'users';
}
echo User::getTableName(); // Outputs: generic_tableIn this case, even though we called
User::getTableName(), the output is
generic_table because self::$tableName was
defined inside the Model class and statically bound to it
at compile time.
The Solution: Late Static Binding with static::
Late static binding solves this issue by introducing the
static:: keyword. Unlike self::, the
static:: keyword instructs PHP to look up the class that
was actually called at runtime.
By replacing self:: with static::, you can
write reusable parent methods that correctly access overridden static
properties and methods in child classes.
Here is the corrected example using late static binding:
class Model {
protected static $tableName = 'generic_table';
public static function getTableName() {
return static::$tableName;
}
}
class User extends Model {
protected static $tableName = 'users';
}
echo User::getTableName(); // Outputs: usersBecause of static::, PHP waits until the code runs,
identifies that User was the class that initiated the call,
and accesses User::$tableName.
When to Use Late Static Binding
Late static binding is highly useful in several scenarios:
- Active Record Patterns: When building custom ORMs or database models where a base class handles queries but needs to know the specific table name of the child class.
- Factory Methods: When a base static method needs to
instantiate the specific child class that called it (e.g.,
return new static();). - Static Helper Classes: When extending utility classes that require overridden configuration properties.
Summary: self:: vs static::
self::refers to the class in which the code is written. It is resolved at compile-time.static::refers to the class that was explicitly called at runtime. It is resolved at runtime and enables late static binding.