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

问题描述 投票:1回答:1

让我们记住这两个美丽的课程!

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

有谁愿意解释输出值是什么以及为什么?

我关注这段代码......打印出“Bar :: testPrivatenFoo :: testPublicn”!为什么?我怎么想看到这个输出?公共方法被重载,私有方法不会被重载。

好的,所以ShowBar()我希望输出“Bar :: testPrivaten”它输出“Bar :: testPublicn”,很棒。

好的,所以ShowFoo()我希望输出“Bar :: testPrivaten”,但实际输出“Foo :: testPublicn”。嗯,为什么?

php class object inheritance override
1个回答
1
投票

下面的代码将触发Bar类中的test()方法,因为你不会覆盖Foo类中的test()方法

$myFoo = new Foo();
$myFoo->test();

因此,此方法将从Bar类触发

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

当您调用$ this-> testPrivate()时,它将打印出Bar的testPrivate()为Bar :: testPrivaten,因为私有方法是私有的,无法覆盖

接下来,您调用$ this-> testPublic()。由于您已经在Foo类中重写了此方法,因此它将从Foo而不是Bar触发testPublic()方法。因此它将打印Foo :: testPublicn

所以你最终会成为Bar :: testPrivatenFoo :: testPublicn

但是没有机会发生这种情况

Ok, so ShowBar() I would expect will output "Bar::testPrivaten" It outputs "Bar::testPublicn", great.
Ok, so ShowFoo() I would expect will output "Bar::testPrivaten" but it actually outputs "Foo::testPublicn".

我刚测试了你的代码,得到了以下内容

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

请确保给出正确的结果

© www.soinside.com 2019 - 2024. All rights reserved.