Hello Readers,
Today we will discuss about PHP 5.3 new feature that is "Late static binding".
PHP 5.3 has introduced a new feature called "late static binding". late static binding can be used to call a class in a context static inheritance.
Before starting the late static binding topic let's first discuss about the two keywords ie. "self" and "static" in PHP.
In PHP, We use the self keyword for accessing the static methods and property of the classes. Keyword "static" resolved at compile time, means when a class is inherited from another class, keyword "self" will always related with the class where it is define, not the class where it is inheriting.
Here is the following example to use of keyword "self":
<?php
class Welcome{
public static function display(){
echo 'Display function of Welcome class';
}
public function callDisplay()
{
self::display();
}
}
$obj = new Welcome;
$obj->callDisplay();
?>
But, here was one limitation with "self" keyword. Below is the example for keyword "self" limitation.
<?php
class Db_query
{
protected static $tableName = "employee_detail";
public function insert()
{
echo "INSERT INTO ". self::$tableName;
}
public function select()
{
echo "SELECT * FROM ". self::$tableName;
}
public function delete()
{
echo "DELETE FROM ". self::$tableName ." WHERE id = 1";
}
}
class User_Account extends Db_query
{
protected static $tableName = "user_account";
}
class User_Posts extends Db_query
{
protected static $tableName = "user_posts";
}
$useraccount = new User_Account;
$useraccount->select();
?>
Output : "SELECT * FROM employee_detail";
In above example, if we create object of "User_Account" class and call the select function, then it will return sql query with "employee_detail" table name. While we define the table name "user_account" in "User_Account" table.
To resolve the limitation, late static binding comes in the PHP 5.3. Late static binding helps in resolving this limitation by introducing a keyword that references the class which was initially called at runtime. It was decided not to introduce a new keyword but preferably use static that was already reserved in PHP.
In the above example by just replacing the self keyword with the static output of the code will change.
<?php
class Db_query
{
protected static $tableName = "employee_detail";
public function insert()
{
echo "INSERT INTO ". static::$tableName;
}
public function select()
{
echo "SELECT * FROM ". static::$tableName;
}
public function delete()
{
echo "DELETE FROM ". static::$tableName ." WHERE id = 1";
}
}
class User_Account extends Db_query
{
protected static $tableName = "user_account";
}
class User_Posts extends Db_query
{
protected static $tableName = "user_posts";
}
$useraccount = new User_Account;
$useraccount->select();
?>
Output : "SELECT * FROM user_account";
0 Comment(s)