继承在创建时起作用,即使用关键字 'new'。静态属性使我对理解感到困惑,因此为了展示可见性对继承的影响,我创建了一个简单的演示脚本,以及一些 set 和 get 魔术
<?php
class A {
private $a = 'private';
protected $b = 'protected';
public $c = 'public';
static $d = 'static';
public function __construct()
{
$this->e = 'constructed';
}
public function __set($property, $value)
{
echo ' set ' . $property . '=' . $value;
$this->$property=$value;
}
public function __get($property)
{
echo ' get ' . $property;
$this->$property = 'dynamic'; return $this->$property;
}
}
class B extends A
{
public function constructMe()
{
$this->e = 'constructed2';
}
}
class C extends B
{
public function __construct()
{
parent::constructMe();
}
}
echo " \n";
$a = new A();
$b = new B();
echo " \n";
echo ' B:c='.$b->c;
echo " \n";
echo ' B:d=' .$b->d;
echo " \n";
$c = new C();
echo " \n";
print_r($a);
print_r($b);
print_r($c);
print_r(A::$d);
print_r(B::$d);
print_r(C::$d);
echo 'A class: ';
$R = new reflectionclass('A');
print_r($R->getdefaultproperties());
print_r($R->getstaticproperties());
echo 'B class: ';
$R = new reflectionclass('B');
print_r($R->getdefaultproperties());
print_r($R->getstaticproperties());
?>
这将输出
set e=constructed
B:c=public
get d set d=dynamic B:d=dynamic
set e=constructed2
A Object
(
[a:A:private] => private
[b:protected] => protected
[c] => public
[e] => constructed
)
B Object
(
[a:A:private] => private
[b:protected] => protected
[c] => public
[d] => dynamic
)
C Object
(
[a:A:private] => private
[b:protected] => protected
[c] => public
[e] => constructed2
)
staticstaticstaticA class: Array
(
[d] => static
[a] => private
[b] => protected
[c] => public
)
Array
(
[d] => static
)
B class: Array
(
[d] => static
[b] => protected
[c] => public
)
Array
(
[d] => static
)
这展示了私有变量 ($a) 如何被继承,静态变量 ($d) 如何被继承(通过类,而不是通过对象),以及在父类中更改或添加变量 ($e, $d) 不会被子类继承。