PHP手册OOP可见性示例-有人可以解释吗 [英] PHP manual OOP visibility example - can someone explain it
问题描述
我在PHP OOP手册 http://www.php.net/manual中看到了这一点. /en/language.oop5.visibility.php ,我无法理解为什么输出不是:Foo :: testPrivate Foo :: testPublic
I saw this in the PHP OOP manual http://www.php.net/manual/en/language.oop5.visibility.php and I can't get my head around why the output is not: Foo::testPrivate Foo::testPublic
class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}
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(); // Bar::testPrivate
// Foo::testPublic
推荐答案
这全部与变量/方法的可见性有关.
It's all about the visibility of the variables / methods.
您会注意到,在Bar
类中,方法testPrivate()
是private
.这意味着只有它自己可以访问该方法.没有孩子.
You'll notice that in the Bar
class, the method testPrivate()
is private
. That means that ONLY itself can access that method. No children.
因此,当Foo
扩展Bar
,然后要求运行test()
方法时,它将执行两件事:
So when Foo
extends Bar
, and then asks to run the test()
method, it does two things:
- 它覆盖了
testPublic()
方法,因为它是公共的,并且Foo
有权使用其自己的版本覆盖它. - 它在
Bar
上调用test()
(因为test()
仅在Bar()
上存在).
- It overrides the
testPublic()
method because it's public, andFoo
has the right to override it with it's own version. - It calls
test()
onBar
(sincetest()
only exists onBar()
).
testPrivate()
被不覆盖,并且是保存test()
的类的一部分.因此,将打印Bar::testPrivate
.
testPublic()
被覆盖,并且是继承类的一部分.因此,将打印Foo::testPublic
.
testPrivate()
is not overridden, and is part of the class that holds test()
. Therefore, Bar::testPrivate
is printed.
testPublic()
is overridden, and is part of the inheriting class. Therefore, Foo::testPublic
is printed.
这篇关于PHP手册OOP可见性示例-有人可以解释吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!