【发布时间】:2014-03-06 10:01:28
【问题描述】:
我很难理解以下代码的输出:
class Bar
{
public function test() {
$this->testPublic();
$this->testPrivate();
}
public function testPublic() {
echo "Bar::testPublic\n";
}
private function testPrivate() {
echo "Bar::testPrivate\n";
}
}
class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublic\n";
}
private function testPrivate() {
echo "Foo::testPrivate\n";
}
}
$myFoo = new foo();
$myFoo->test();
输出:
Foo::testPublic
Bar::testPrivate
类 Foo 覆盖 testPublic() 和 testPrivate(),并继承 test()。当我调用 test() 时,有一个包含 $this 伪变量的显式指令,所以在我创建 $myFoo 实例之后,最终调用test() 函数将是 $myFoo->testPublic() 和 $myFoo->testPrivate()。第一个输出如我所料,因为我重写了 testPublic() 方法来回显 Foo::testPublic。但是第二个输出对我来说毫无意义。如果我覆盖 testPrivate() 方法,为什么是 Bar::testPrivate?根据定义,父类的私有方法也不会被继承!这没有道理。为什么调用的是父方法???
【问题讨论】:
-
考虑将
public function test() { $this->testPublic(); $this->testPrivate(); }更改为public function test() { $this->testPublic(); static::testPrivate(); }- 然后阅读late static binding(特别是示例#3) -
@MarkBaker 这些方法是在对象上下文中调用的,而不是静态的,因此后期静态绑定不适用。这是一个简单的可见性问题。
-
@rainfromheaven - 我确实在我的评论中专门引用了 Example #3,“static:: usage in a non-static context”.. .. 即在 object 环境中。后期静态绑定完全按照文档的那部分所述应用
-
@MarkBaker 我收回我之前的声明,你对后期静态绑定是对的 :)
标签: php oop visibility overriding