Child class references static variable of parent instead of its own

Child class references static variable of parent instead of its own

am 17.08.2007 22:51:09 von richardkmiller

Here's an OOP question that perplexes me. It seems PHP doesn't treat
static variables correctly in child classes.

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?

There are several examples of this bug (if it is one) in the comments
for the get_class() function: http://us.php.net/manual/en/function.get-class.php

Best regards,
Richard

Re: Child class references static variable of parent instead of itsown

am 17.08.2007 23:04:16 von Dikkie Dik

The manual says that static variables are not inherited normally:

http://nl3.php.net/manual/pl/language.oop5.static.php

Best regards.

Re: Child class references static variable of parent instead of itsown

am 17.08.2007 23:31:38 von Toby A Inkster

Richard K Miller wrote:

> Here's an OOP question that perplexes me. It seems PHP doesn't treat
> static variables correctly in child classes.

Google: PHP late static binding.

It *might* get fixed in PHP 6, but is unlikely to change in PHP 5.x
because it may break scripts that rely on the current behaviour.

-Toby

Re: Child class references static variable of parent instead of its own

am 17.08.2007 23:59:18 von richardkmiller

On Aug 17, 3:04 pm, Dikkie Dik wrote:
> The manual says that static variables are not inherited normally:
>
> http://nl3.php.net/manual/pl/language.oop5.static.php
>
> Best regards.

Thanks for pointing that out; I hadn't noticed.

Minutes from a meeting about PHP 6 seem to indicate that this will be
fixed:

http://www.php.net/~derick/meeting-notes.html#late-static-bi nding-using-this-without-or-perhaps-with-a-different-name