Re: Suggestion on static field inheritance
| From: | Robin Fernandes | Date: | Mon, 18 May 2009 12:29:35 +0000 |
| Subject: | Re: Suggestion on static field inheritance | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-44024@lists.php.net to get a copy of this message | ||
2009/5/16 Jingcheng Zhang <diogin@gmail.com>:
>
> Maybe I have not found its detailed description on PHP's official manual,
> but PHP does allow static field inheritance. However there is a little
> difference between dynamic field inheritance and static field inheritance,
> as the following codes shows:
Hi!
I think the current behaviour is as expected.
In that example, there is a single static field which is shared
between classes static_a, static_b and static_c. Because there is just
one value of $name, the class through which you access the value makes
no difference. On the other hand, in the case of classes dynamic_a,
dynamic_b and dynamic_c, by the nature of instance properties, each
instance has its own value of $name. So changing the value in one
instance does not affect the others. This behaviour is similar to many
other OO languages, including Java, C++ and C#.
Perhaps a closer equivalent of the Javascript code you provided is as
follows, where the static field is re-declared in subclasses, and
therefore exists as a separate entity in each class. Again, this
distinction between inherited static fields and "re-declared" static
fields also applies to other languages such as Java, C++ and C#.
<?php
class static_a {
public static function change($name) {
static::$name = $name;
}
public static $name = 'a';
}
class static_c extends static_a {
public static $name;
}
class static_d extends static_a {
public static $name;
}
echo static_a::$name; // a
static_c::change('c');
echo static_a::$name; // a
static_d::change('d');
echo static_a::$name; // a
?>
What do you think?
Regards,
Robin