Can someone help me understand variable/function inheritance in PHP classes.
My parent class has a function which is used by all the child classes. However each child classes needs to use it's own variable in this function. I want to call the function in the child classes statically. In the example below, the 'world' is displayed, as opposed to the values in the child classes.
Can anyone explain how I can get the function to echo the values in the child classes. Should I be using interfaces? Is this something to do with late static binding (which is unavailable to me due to using a pre 5.3.0 version of PHP)?
class myParent
{
static $myVar = 'world';
static function hello()
{
echo self::$myVar;
}
}
class myFirstChild extends myParent
{
static $myVar = 'earth';
}
class mySecondChild extends myParent
{
static $myVar = 'planet';
}
myFirstChild::hello();
mySecondChild::hello();
Yeah, you can't do that. The declarations of static $myVar
do not interact with each other in any way, precisely because they are static, and yeah, if you had 5.3.0 you could get around it, but you don't so you can't.
My advice is to just use a non-static variable and method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With