【问题标题】:How to not allow a sub-class method to be defined in PHP如何不允许在 PHP 中定义子类方法
【发布时间】:2011-06-06 08:15:06
【问题描述】:

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

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
  }
}

【问题讨论】:

    标签: php class methods


    【解决方案1】:

    使用 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
      }
    }
    

    PHP Final keyword。注意foo 仍然会有一个方法something,但something 只会来自fooBase,而foo 不能覆盖它。

    【讨论】:

    • __construct 方法也可以是最终的(如果 fooBase 有的话)?
    • 是的,__construct 可以是最终的。如果你在父类中说它是 final 的,那么你不能在子类中拥有它。
    • 确实,正如 SamT 所说,您可以将 __construct 设为 final。
    【解决方案2】:

    使用 final 关键字。

    在你的父母中:

    final public function something()
    

    【讨论】:

      【解决方案3】:

      您可以使用final 来防止基方法被覆盖。

      class fooBase{
      
        final public function something(){
      
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        • 2011-07-17
        • 2010-09-09
        相关资源
        最近更新 更多