如何不允许在PHP中定义子类方法

Ale*_*lex 2 php methods class

如何防止something在foo类中创建以下方法?

class fooBase{

  public function something(){

  }
}

class foo extends fooBase{

  public function __construct(){
    echo $this->something(); // <- should be the parent class method
  }

  public function something(){ 
    // this method should not be allowed to be created
  }
}
Run Code Online (Sandbox Code Playgroud)

MGw*_*nne 10

使用final关键字(如Java等):

class fooBase{

  final public function something(){

  }
}

class foo extends fooBase{

  public function __construct(){
    echo $this->something(); // <- should be the parent class method
  }

  public function something(){ 
    // this method should not be allowed to be created
  }
}
Run Code Online (Sandbox Code Playgroud)

请参阅PHP Final关键字.请注意,foo仍然会有一个方法something,但something只会来自fooBase并且foo不能覆盖它.

  • 是的,__construct可以是最终的.如果你说它在父类中是最终的,你就不能在孩子中有一个. (2认同)