Posts

Showing posts with the label self

PHP static as virtual self, what else for parent?

I find the static keyword in PHP 5.3 absolutely useful, but I instantly felt into a dilemma: what about parent? With static it is possible to refer to a generic class static property, without referring the class where the method has been declared. Here there is a simple example: class Numbers { public static $value = 0; public static function getValue(){ return static::$value; } } class One extends Number { public static $value = 1; } class Two extends Number { public static $value = 2; } $one = new One; $two = new Two; $one->getValue(); // 1 $two->getValue(); // 2 Above example shows how static behaves when an instance calls a method which uses static keyword. Whatever subclass it is, we will always obtain the defined value (if any, otherwise the inherited one) as expected. But what about parent behavior? If we use parent inside a method it is like using self, the parent keyword will always refers to the parent class, if any, of the method which conta...