On Aug 16, 2007, at 5:48 PM, Alvaro Carrasco wrote:

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


Alvaro, thanks for this explanation; this was very helpful. I sincerely hope that PHP6 implements late static binding.

Do you see anyway around this? My parent class is a generic database table wrapper to provide ORM mapping. Each child class maps to a specific table. I'd like to implement several static functions such as search_by(), a factory pattern that returns an object or objects of its own class that match the search. I see no way to define the database table in a child class and have it passed back to a static function in the parent class.

Richard



_______________________________________________

UPHPU mailing list
[email protected]
http://uphpu.org/mailman/listinfo/uphpu
IRC: #uphpu on irc.freenode.net

Reply via email to