[UPHPU] Child class references static variable of parent instead of its own

Alvaro Carrasco alvaro at epliant.com
Thu Aug 16 17:48:05 MDT 2007


Richard K Miller wrote:
> Here's an OOP question that perplexes me. It seems PHP doesn't treat 
> static variables correctly in child classes.
>
> <?php
>     class ABC {
>         public $regular_variable = "Regular variable in ABC\n";
>         public static $static_variable = "Static variable in ABC\n";
>     
>         public function regular_function() {
>             echo $this->regular_variable;
>         }
>        
>         public static function static_function() {
>             echo self::$static_variable;
>         }
>     }
>
>     class DEF extends ABC {
>         public $regular_variable = "Regular variable in DEF\n";
>         public static $static_variable = "Static variable in DEF\n";
>     }
>
>     $abc = new ABC();
>     $abc->regular_function();
>     ABC::static_function();
>
>     $def = new DEF();
>     $def->regular_function();
>     DEF::static_function();
> ?>
>
> WHAT I EXPECTED:
> Regular variable in ABC
> Static variable in ABC
> Regular variable in DEF
> Static variable in DEF
>
> ACTUAL OUTPUT:
> Regular variable in ABC
> Static variable in ABC
> Regular variable in DEF
> Static variable in ABC <--- This is different from what I expected
>
> Anyone know why?
>
> Richard
>
>
"self" is bound to the class at compile time, not at runtime. So when 
you do:

echo self::$static_variable

It's the same as doing

echo ABC::$static_variable

because "self" was bound to ABC when the class was defined.
It is more of an implementation limitation in php than an intended feature.

For version 6, the php dev team is considering to do late-static 
binding, which would bind "self" to a class at runtime instead of 
compile time, but they haven't flushed out all of the details.

Alvaro



More information about the UPHPU mailing list