Why in late static binding child class gets data from parent and current methods
Ok, the title is hard to understand, but I was trying to understand about late static binding, and I saw this answer https://stackoverflow.com/a/35577069/1640606
Which shows the difference as being between those two example:
Note, self::$c
class A
{
static $c = 7;
public static function getVal()
{
return self::$c;
}
}
class B extends A
{
static $c = 8;
}
B::getVal(); // 7
Late static binding, note static::$c
class A
{
static $c = 7;
public static function getVal()
{
return static::$c;
}
}
class B extends A
{
static $c = 8;
}
B::getVal(); // 8
Now, I understand this, but what I don't get is, why the B::getVal(); // 8
B::getVal(); // 8
first gets the getVal
from class A
, but seems to get the value defined in class B
.
So, ``B::getVal();` is getting the method of the class, but the value of the second class. My question is, is this the real intended purpose of the late static binding and what does it help to resolve
Example 1:
class A
{
static $c = 7;
public static function getVal()
{
return self::$c;
}
}
class B extends A
{
static $c = 8;
}
B::getVal(); // 7
In Example 1 it is returning you 7 because when you invoke getVal
function on B
then PHP find its declaration in its parent class which is returning the value of $c
from current class using operator self
.
Example 2:
class A
{
static $c = 7;
public static function getVal()
{
return static::$c;
}
}
class B extends A
{
static $c = 8;
}
B::getVal(); // 8
But in example 2 when you invoke getVal
then again php finds its declaration in its parent class, but class is returning return static::$c
which means return the value of the variable of class from which its is invoked.