2017-02-16 117 views
0

我想实现一个代码有点像下面,但无法理解一个问题,按我的理解,它应该已经印像这样的数据:PHP面向对象编程哎呀问题

Foo::testPrivate 
Foo::testPublic 

但它的显示输出::

Bar::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(); 

有人可以请实验值躺在这?

+0

编辑后的返回'Bar :: testPrivate Foo :: testPublic' – Peon

+5

小孩不能覆盖私人函数。 –

+0

The docs:http://php.net/manual/en/language.oop5.visibility.php –

回答

0

按我的理解

  • 显示输出是正确的,因为你正在创建“富”类的对象,然后后拨测()函数是“棒”类中

  • 在试验(+)酒吧类的函数调用是使用“this”关键字,以便调用同一类和testPrivate()函数testPrivate()也是私人所以这就是为什么显示的结果一样:

酒吧:: testPrivate
富:: testPublic

  • 进行更改私有函数testPrivate() {}到公共职能testPrivate()在两个类显示在您的接受结果
  • 作出后这改变
  • 结果是:

富:: testPrivate
Foo :: testPublic