PHP Late Static Binding
Summary: in this tutorial, you will learn about the PHP late static binding, which is an interesting feature that has been added to the PHP 5.3
Introduction to late static binding in PHP
Let’s start with a simple example.
class Model
{
protected static $tableName = 'Model';
public static function getTableName()
{
return self::$tableName;
}
}
class User extends Model
{
protected static $tableName = 'User';
}
echo User::getTableName(); // Model, not User
Code language: HTML, XML (xml)
How it works.
- First, create a
Modelclass that has$tableNamestatic property with the value Model and agetTableName()static method that returns the value of the$tableName. - Second, create another class called
Userthat extends theModelclass. TheUserclass also has$tableNamestatic attribute. - Third, call the
getTableName()method of theUserclass. However, it returnsModelinstead ofUser. The reason is thatselfis resolved to the class in which the method belongs. If you define a method in a parent class and call it from a subclass, itselfdoes not reference the subclass as you might expect.
To resolve this issue, PHP 5.3 introduced a new feature called PHP static late binding.
Instead of using the self, you use the static keyword that references an exact class that is called at runtime.
Let’s modify our example above:
class Model
{
protected static $tableName = 'Model';
public static function getTableName()
{
return static::$tableName;
}
}
class User extends Model
{
protected static $tableName = 'User';
}
echo User::getTableName(); // User
Code language: HTML, XML (xml)
Now you get the expected result.