ren*_*tov 3 php oop overriding visibility
我很难理解以下代码的输出:
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();
Run Code Online (Sandbox Code Playgroud)
输出:
Foo::testPublic
Bar::testPrivate
Run Code Online (Sandbox Code Playgroud)
Foo类重写testPublic()和testPrivate(),并继承test()。当我调用test()时,有一条包含$ this伪变量的显式指令,因此在创建$ myFoo实例之后,test()函数的最终调用将是$ myFoo-> testPublic()和$ myFoo-> testPrivate( )。第一个输出与我预期的一样,因为我覆盖了testPublic()方法以回显Foo :: testPublic。但是第二个输出对我来说毫无意义。如果我覆盖了testPrivate(),为什么它是Bar :: testPrivate方法?根据定义,父类的私有方法也不会被继承!这没有道理。为什么父方法被称为???
您的代码的问题在于方法Bar::testPrivate是private,因此子类不能覆盖它。首先,我建议您阅读PHP的可见性-http: //www.php.net/manual/zh/language.oop5.visibility.php。在那里,你会知道只有public和protected类成员方法/属性可以被覆盖,private那些不能。
作为一个很好的例子,请尝试将Bar::testPrivate方法的可见性更改为public或protected,而不更改示例代码中的任何其他内容。现在尝试运行测试。怎么了?这个:
PHP致命错误:对Foo :: testPrivate()的访问级别必须受保护(如在Bar类中)或更弱
最大的问题是:“为什么?”。好了,您现在已经被Bar::testPrivateprivate 覆盖了Foo:testPrivate。此新的私有方法不在的范围内Bar::test,因为私有类成员仅对当前类可见,而对父/子类不可见!
因此,如您所见,OOP为类成员提供了一定数量的封装,如果您不花时间去理解它,可能会造成很大的混乱。