我发现在
PHP中似乎是一个奇怪的继承问题.
Members declared protected can be accessed only within the class
itself and by inherited and parent classes.
对我而言意味着:
A可以访问B的受保护成员,如果A或B的实例A
但是,如果A和B都扩展了Foo,而Foo有一个受保护的构造函数,在B中没有被覆盖,那么我可以在A内创建一个B的实例.这对我来说没有意义,因为A不是B和B不是A的实例.我也可以调用A中的保护方法$b-> test(),它执行在B中实现的方法(如果B不重新测试test(),那么执行Foo被执行.)对我来说这更奇怪,因为如果B直接实现受保护的构造函数,我不能从A内创建一个B的实例.看起来很奇怪,我无法访问受保护的构造函数(也在父类中声明),但访问受保护的方法(也在父类中声明)是没有问题的.
注意,当我使用不扩展Foo的类C时,我会得到预期的行为.如果我尝试从C中实例化B,我会遇到一个致命的错误,因为我正在尝试访问受保护的构造函数.如果我向B添加一个公共构造函数,可以实例化(这是预期的),我仍然无法访问受保护的方法test()(这也是预期的行为).使用A而不是C时,我期待同样的行为.
示例代码再次解释:
class Foo {
protected function __construct() {
echo('Constructing ' . get_called_class());
}
protected function test() {
echo('Hello world ' . __METHOD__);
}
}
class A extends Foo {
public function __construct() {
parent::__construct();
}
public function testB() {
// Both of these lines work
$b = new B();
$b->test();
}
}
class B extends Foo {
protected function test() {
echo('Hello world Again ' . __METHOD__);
}
}
class C {
public function __construct() {
}
public function testB() {
// Both of these lines cause fatal errors
$b = new B();
$b->test();
}
}
$a = new A();
$a->testB();
$c = new C();
$c->testB();
我可能没看到什么,但我找不到什么.有人可以向我解释这个行为吗?