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 as of PHP 5.3
Let’s start with a simple example.
How it works.
- First, we created a
Modelclass that has$tableNamestatic property with value Model and agetTableName()static method that returns the value of the$tableName. Notice that we used theselfand the operator :: to access static property inside the Model class. - Second, we created another class named
Userthat extends theModelclass. The User class also has$tableNamestatic attribute. - Third, we called the
getTableName()method of theUserclass. However, it returns Model instead of User. The reason is thatselfis always resolved to the class in which the method belongs. It means that if you define a method in a parent class and call it from a subclass, theselfdoes not reference to the subclass as we expect.
To overcome this issue, as of version 5.3, PHP introduced a new feature called PHP static late binding. Basically, instead of using the
self, you use the static keyword that references to the exact class that was called at runtime.
Let’s modify our example above:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?php
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
|
No comments:
Post a Comment