Php 当类继承类时,方法重写如何工作?

Php 当类继承类时,方法重写如何工作?,php,class,object,inheritance,overriding,Php,Class,Object,Inheritance,Overriding,让我们记住这两个美丽的班级 class Bar { public function test() { echo "<br>"; $this->testPrivate(); $this->testPublic(); } public function testPublic() { echo "Bar::testPublicn"; } private function

让我们记住这两个美丽的班级

class Bar 
{
    public function test() {
        echo "<br>";
        $this->testPrivate();
        $this->testPublic();
    }

    public function testPublic() {
        echo "Bar::testPublicn";
    }

    private function testPrivate() {
        echo "Bar::testPrivaten";
    }

    public function ShowBar() {
        $this->testPrivate();
    }
}

class Foo extends Bar 
{
    public function testPublic() {
        echo "Foo::testPublicn";
    }

    private function testPrivate() {
        echo "Foo::testPrivaten";
    }

    public function ShowFoo() {
        $this->testPrivate();
    }
} 
$myFoo = new Foo();
$myFoo->test();

echo "<br>"; 
$myFoo->ShowBar();

echo "<br>"; 
$myFoo->ShowFoo(); 
类栏
{
公共功能测试(){
回声“
”; $this->testPrivate(); $this->testPublic(); } 公共函数testPublic(){ echo“Bar::testPublicn”; } 私有函数testPrivate(){ echo“Bar::testPrivaten”; } 公共功能显示栏(){ $this->testPrivate(); } } 类Foo扩展条 { 公共函数testPublic(){ echo“Foo::testPublicn”; } 私有函数testPrivate(){ echo“Foo::testPrivaten”; } 公共功能ShowFoo(){ $this->testPrivate(); } } $myFoo=新Foo(); $myFoo->test(); 回声“
”; $myFoo->ShowBar(); 回声“
”; $myFoo->ShowFoo();
有人愿意解释输出值是什么以及为什么

我正在关注这个代码。。。 它打印“Bar::testprivatenfo::testPublicn”!为什么? 我是如何看待这个输出的? 公共方法重载,私有方法不重载

好的,我希望ShowBar()会输出“Bar::testPrivaten” 它输出“Bar::testpublign”,非常好

好的,我希望ShowFoo()将输出“Bar::testPrivaten” 但它实际上输出“Foo::testpublign”。
嗯,为什么?

下面的一段代码将在Bar类中触发test()方法,因为您不会重写Foo类中的test()方法

$myFoo = new Foo();
$myFoo->test();
因此,此方法将从Bar类中激发

public function test() {
    echo "<br>";
    $this->testPrivate();
    $this->testPublic();
}
我刚刚测试了你的代码,得到了以下结果

Bar::testPrivatenFoo::testPublicn
Bar::testPrivaten
Foo::testPrivaten

请确保给出正确的结果

第三个Foo类是什么?您正在使用私有和公共方法。只能重写公共和受保护的方法,不能重写私有方法。另外,您在这里称为重载,但您尝试的是重写。我删除了第三个Foo类。很抱歉误解了术语,我刚刚编辑过。
Bar::testPrivatenFoo::testPublicn
Bar::testPrivaten
Foo::testPrivaten