考虑以下代码:
class foo { private function m() { echo 'foo->m() '; } public function call() { $this->m(); } } class bar extends foo { private function m() { echo 'bar->m() '; } public function callbar() { $this->m(); } } $bar = new bar; $bar->call(); $bar->callbar();
现在,更改m()方法的可见性,我得到: (+for public,-for private)
m()
+
public
-
private
Visibility bar->call() bar->callbar() ====================================================== -foo->m(), -bar->m() foo->m() bar->m() -foo->m(), +bar->m() foo->m() bar->m() +foo->m(), -bar->m() ERROR ERROR +foo->m(), +bar->m() bar->m() bar->m()
(protected看起来像public)。
protected
我期望所有东西都像声明时一样public。但是,尽管foo->call()和bar->callbar()本质上是同一件事,但根据m()in foo和的可见性,它们会产生不同的结果bar。为什么会这样?
foo->call()
bar->callbar()
foo
bar
在PHP中,子类中的方法(包括私有方法)为:
您可以使用以下代码查看此内容:
<?php class A { //calling B::h, because static:: resolves to B:: function callH() { static::h(); } private function h() { echo "in A::h"; } } class B extends A { //not necessary; just to make explicit what's happening function callH() { parent::callH(); } } $b = new B; $b->callH();
现在,如果您覆盖私有方法,则它的新作用域将不是A,它将成为B,并且调用将因为A::callH()在scope中运行而失败A:
A::callH()
A
<?php class A { //calling B::h, because static:: resolves to B:: function callH() { static::h(); } private function h() { echo "in A::h"; } } class B extends A { private function h() { echo "in B::h"; } } $b = new B; $b->callH(); //fatal error; call to private method B::h() from context 'A'
这里的规则如下:
bar->call()
call
$this->m()
m
bar::m()
foo:m()