【问题标题】:PHP Object Oriented Programming Oops IssuesPHP 面向对象编程糟糕问题
【发布时间】:2017-07-05 12:01:15
【问题描述】:

我正在尝试实现类似于下面的代码,但无法理解一个问题,根据我的理解,它应该像这样打印数据:

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

有人可以解释一下吗?

【问题讨论】:

  • 编辑返回Bar::testPrivate Foo::testPublic
  • 子不能覆盖私有函数。
  • 在父类定义的方法中调用“$this->testPrivate()”,如果定义了父私有方法testPrivate(根据定义,它们不能被覆盖)。如果它是受保护的或公共的,它将尝试首先执行子类方法(如果它已定义,否则它将查看父类中的现有方法)..

标签: php oop object inheritance


【解决方案1】:

根据我的理解

  • 显示输出是正确的,因为您创建了“Foo”类的对象,然后调用 test() 函数后位于“Bar”类中

  • 在 Bar 类的 test() 函数中,使用 "this" 关键字调用 testPrivate(),因此在同一个类中调用该函数,并且 testPrivate() 也是私有的,因此显示结果如下:

酒吧::testPrivate
Foo::testPublic

  • 将两个类中的 private function testPrivate() { } 更改为 public function testPrivate() 以显示您接受的结果
  • 进行此更改后的结果是:

Foo::testPrivate
Foo::testPublic

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-09
    • 2011-07-25
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多