Why does late static binding work with variables in PHP 5.3?

Let's start with the code:

class Super { protected static $color; public static function setColor($color){ self::$color = $color; } public static function getColor() { return self::$color; } } class ChildA extends Super { } class ChildB extends Super { } ChildA::setColor('red'); ChildB::setColor('green'); echo ChildA::getColor(); echo ChildB::getColor(); 

Now, late static binding in PHP 5.3 using the static keyword works fine with static methods, so I assumed that it would do the same magic on static variables. Well, that doesn't seem to be the case. The above example does not print โ€œredโ€ and then โ€œgreenโ€, as I expected, but โ€œgreenโ€ and โ€œgreenโ€. Why does this not work with variables when working on methods? Is there any other way to achieve the expected effect?

+6
source share
1 answer

Later, static binding will only work for new variable / method definitions. Thus, in your example, the $color Super property will always be changed instead of ChildA or ChildB . To use late static binding, you need to use the static instead of self . In addition, you need to override the $color property for the ChildA and ChildB :

 class Super { protected static $color; public static function setColor($color){ // static instead of self static::$color = $color; } public static function getColor() { // static instead of self return static::$color; } } class ChildA extends Super { protected static $color; } class ChildB extends Super { protected static $color; } ChildA::setColor('red'); ChildB::setColor('green'); echo Super::getColor(); // prints nothing (NULL = ''), expected echo ChildA::getColor();// prints red echo ChildB::getColor();// prints green 
+11
source

Source: https://habr.com/ru/post/888094/


All Articles