【问题标题】:How method overriding works when class inherits class?类继承类时方法覆盖如何工作?
【发布时间】:2019-02-08 18:34:49
【问题描述】:

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

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::testPrivateFoo::testPublicn”!为什么? 我怎么想看到这个输出? 公共方法重载,私有方法不重载。

好的,我希望 ShowBar() 会输出“Bar::testPrivate” 它输出“Bar::testPublicn”,太棒了。

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

【问题讨论】:

  • 什么是 3rd Foo 类?您正在搞乱私有和公共方法。只有公共和受保护的方法可以被覆盖,而不是私有的。此外,您在这里将其称为重载,但您尝试过的是覆盖。
  • 我删除了第 3 个 Foo 类。对不起,我刚刚编辑了条款。

标签: php class object inheritance overriding


【解决方案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::testPrivate 因为私有方法是类私有的,不能被覆盖

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

所以你最终会成为 Bar::testPrivateFoo::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

请确保给出正确的结果

【讨论】:

    猜你喜欢
    • 2012-11-20
    • 2014-01-15
    • 2012-09-27
    • 1970-01-01
    • 2016-12-03
    • 2021-11-30
    • 2016-01-24
    • 1970-01-01
    • 2012-10-15
    相关资源
    最近更新 更多