PHP function and variable inheritance

Can someone help me understand the inheritance of variables / functions in PHP classes.

My parent class has a function that is used by all child classes. However, each child class must use its own variable in its function. I want to call a function in child classes statically. The example below displays "world" rather than values ​​in child classes.

Can anyone explain how I can force the echo value function in child classes. Should I use interfaces? Is this due to late static binding (which is not available to me due to using PHP version 5.3.0)?

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(); 
+4
source share
4 answers

Yes, you cannot do this. The static $myVar declarations do not interact with each other in any way, precisely because they are static, and yes, if you had 5.3.0, you could get around it, but you won’t.

My advice is to simply use non-static variables and methods.

+2
source

You can do it as follows:

 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 
+1
source

IF you are using PHP 5.3, this echo statement will work:

 echo static::$myVar; 

But since this is not available to you, your only (good) option is to make the hello() function not static.

0
source

I want to call a function in child classes statically.

It really will cause you in trouble that will get to the end of the day ^^ (This is already possible, maybe ^^)

I would 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 since PHP 5.3 is completely new, it probably won't be available on your hosting until a few months ...

0
source

All Articles