Php is now widening its scope and solving its limitation to achieve the pure OOP(Object Oriented Programmng).
Now we will learn the LSB by observing the code:
<?php
class parentclass
{
public static $c_name = __class__;
/*this will store the name of the class in $_cname*/
function get_class_name(){
echo”This is the object of “;
return self::$c_name.'<br/>’;
}
}
class subclass1 extends parentclass{public static $c_name = __class__;}
class subclass2 extends subclass1 {public static $c_name = __class__;}
$obj_parentclass = new parentclass();
$obj_subclass1 = new subclass1 ();
$obj_subclass2 = new subclass2 ();
echo $obj_parentclass->get_class_name();
echo $obj_subclass1->get_class_name();
echo $obj_subclass2->get_class_name();
?>
The output:
This is the object of parentclass
This is the object of parentclass
This is the object of parentclass
And i think you already astonished by observing that from wherever the childclass you invoked the method it always shows the name for parent class.
So definitely its a problem that you cant tell from which class in your class hierarchy was invoked.
So now we will go the solution. we will use the LSB to get rid of this.
Just change the function get_class_name();
before it was
function get_class_name(){
echo”This is the object of “;
return self::$c_name.'<br/>’;
}
Now it will be
function get_class_name(){
echo”This is the object of “;
return static::$c_name.'<br/>’; // Here the code change for Late Static Bindings
}
And you will show the output like this:
This is the object of parentclass
This is the object of subclass1
This is the object of subclass2
For sake of total understandings now the code is again with little change:
<?php
class parentclass
{
public static $c_name = __class__;
/*this will store the name of the class in $_cname*/
function get_class_name(){
echo”This is the object of “;
return static::$c_name.'<br/>’;
}
}
class subclass1 extends parentclass{public static $c_name = __class__;}
class subclass2 extends subclass1 {public static $c_name = __class__;}
$obj_parentclass = new parentclass();
$obj_subclass1 = new subclass1 ();
$obj_subclass2 = new subclass2 ();
echo $obj_parentclass->get_class_name();
echo $obj_subclass1->get_class_name();
echo $obj_subclass2->get_class_name();
?>
Cheers. i think now you understand the LSB.
N.B: This code is valid for php 5.3.0
Thanks for your times. Be happy.