tags:

views:

289

answers:

5

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();
A: 

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.

too much php
+1  A: 

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.

chaos
I've decided to create an instance of 'self' inside the children's static functions, then store the variables as non-static.
Rowan Parker
A: 

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...

Pascal MARTIN
A: 

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
Johan
A: 

To Johan:

thank you for your answers. And I have a stupid question. I tried your solution by using JAVA (the same structure, but just different syntax), but the results will show like : 
world
world

I just wonder it's beucase the different OO ways between JAVA and PHP!? Or...!? Thank you very much for solvig my puzzles!

Andrew

andrew