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
Model
class that has$tableName
static property with value Model and agetTableName()
static method that returns the value of the$tableName
. Notice that we used theself
and the operator :: to access static property inside the Model class. - Second, we created another class named
User
that extends theModel
class. The User class also has$tableName
static attribute. - Third, we called the
getTableName()
method of theUser
class. However, it returns Model instead of User. The reason is thatself
is 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, theself
does 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