Reputation: 794
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();
Upvotes: 5
Views: 6896
Reputation: 20763
You could do it like this:
class myParent
{
var $myVar = "world";
function hello()
{
echo $this->myVar."\n";
}
}
class myFirstChild extends myParent
{
var $myVar = "earth";
}
class mySecondChild extends myParent
{
var $myVar = "planet";
}
$first = new myFirstChild();
$first->hello();
$second = new mySecondChild();
$second->hello();
This code prints
earth
planet
Upvotes: 1
Reputation: 400932
I want to call the function in the child classes statically.
This will really drive you into troubles that'll get you nuts before the end of the day ^^ (It already has, maybe ^^ )
I would defintly recommend using as few "static
" properties/methods as possible, especially if you are trying to work with inheritance, at least with PHP < 5.3
And as PHP 5.3 is quite new, it probably won't be available on your hosting service before a couple of months...
Upvotes: 0
Reputation: 124267
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.
Upvotes: 2
Reputation: 90978
IF you were using PHP 5.3, this echo statement would work:
echo static::$myVar;
But since that is unavailable to you, your only (nice) option is to make the hello()
function not static.
Upvotes: 0