Hello all,
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:
<?php
class static_a {
public static function change($name) {
self::$name = $name;
}
public static $name = 'a';
}
class static_c extends static_a {}
class static_d extends static_a {}
echo static_a::$name; // a
static_c::change('c');
echo static_a::$name; // c
static_d::change('d');
echo static_a::$name; // d
class dynamic_a {
public function change($name) {
$this->name = $name;
}
public $name = 'a';
}
class dynamic_c extends dynamic_a {}
class dynamic_d extends dynamic_a {}
$a = new dynamic_a();
$c = new dynamic_c();
$d = new dynamic_d();
echo $a->name; // a
$c->change('c');
echo $a->name; // a
$d->change('d');
echo $a->name; // a
?>
The result of static inheritance test can be meaningful on some
way(especially on class-based programming perspective), but when considering
the static class as "object" in prototype-based programming(which I doubt is
some people's favourite who comes from prototype-based OOP community), this
result can be confusing. On JavaScript, this example can be:
<script type="text/javascript">
function extends(parent) {
var T = function () {};
T.prototype = parent;
return new T();
}
var static_a = {
name: 'a',
change: function (name) {
this.name = name;
}
};
var static_c = extends(static_a);
var static_d = extends(static_a);
alert(static_a.name); // a
static_c.change('c');
alert(static_a.name); // a
static_d.change('d');
alert(static_a.name); // a
</script>
This looks more meaningful. So my suggestion is, could PHP's static
inheritance rule follow the dynamic inheritance rule ( $this on dynamic, or
prototype delegation on JavaScript) ?
Thanks :-)
--
Best regards,
Jingcheng Zhang
P.R.China