child class 中可以覆盖私有方法吗

can private methods be over ridden in child class

这是一个示例,如果方法的访问类型是 public,child class 方法可以覆盖 parent 方法 例如:

class Foo {

  public function fun1() {
    echo "Hello World";
  }

  public function callMe(){
    $this->fun1();
  }
}


class Bar extends Foo {

  public function fun1(){
    echo "check this out";
  }
}

$bar = new Bar();
$bar->callMe(); //this would print "check this out"

但是如果 fun1 在 parent class Foo 中被授予 private 访问权限,那么该方法将不再被滥用。

例如:

class Foo {

  private function fun1() {
    echo "hello world";
  }

  public function callMe(){
    $this->fun1();
  }
}

在这种情况下,输出将为 hello world
我想知道,即使访问类型为 private?

,是否可以通过扩展 class 覆盖方法 fun1

不知道 PHP 但根据 OOP 概念 NO 因为带有访问修饰符 private 的方法虽然存在但不能覆盖或访问 child class。如果您想将其覆盖为 child class 然后尝试将访问修饰符更改为 publicprotected