【问题标题】:Why $this calling parent method instead self method (there is same method in parent and self)? [duplicate]为什么 $this 调用父方法而不是 self 方法(父方法和 self 方法相同)? [复制]
【发布时间】:2021-04-08 17:04:21
【问题描述】:
class ParentClass
{
  private function foo()
  {
    echo 'foo() in ParentClass';
  }
  public function test()
  {
    echo $this::class; // ChildClass
    $this->foo();
  }
}

class ChildClass extends ParentClass
{
  private function foo()
  {
    echo 'foo() in ChildClass';
  }
}

$o = new ChildClass();
$o->test(); // 'foo() in ParentClass';

我希望结果是 'foo() in ChildClass'。

我的问题是为什么 $this->foo();test() 中调用 foo() 在 ParentClass 而不是在 ChildClass 中?为什么它没有被覆盖?

【问题讨论】:

    标签: php oop inheritance


    【解决方案1】:

    protected 替换您的private 可见性修饰符。私有方法不可重用,因此对扩展它们的类隐藏。

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2017-07-20
      • 2013-11-08
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2013-07-27
      • 1970-01-01
      相关资源
      最近更新 更多