Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function and variable inheritance

Tags:

php

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();
like image 908
Rowan Parker Avatar asked Oct 27 '22 03:10

Rowan Parker


1 Answers

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.

like image 100
chaos Avatar answered Oct 29 '22 14:10

chaos