PHP子类可以改变重写方法的参数吗?

时间:2012-07-26 21:47:28

标签: php oop

我可以覆盖子类中的PHP方法并更改签名中的参数,如下所示。

class theParent {
  function myMethod($param1) {
    // code here
  }
}

class theChild extends theParent {
  function myMethod($param1, $param2) {
    // code here
  }
}

我对此进行了测试,它工作正常,不会引发任何错误。我的问题是,这是不好的形式?还是OOP的基本原则?

如果父方法被声明为abstract,则子签名不能偏离。据推测,如果您需要强制执行界面的这一方面,这是使用的机制吗?

3 个答案:

答案 0 :(得分:3)

您将通过不匹配父类的该方法的参数数量来抛出严格的标准错误消息。

此处有更多信息......

Why is overriding method parameters a violation of strict standards in PHP?

答案 1 :(得分:0)

只要

class theChild extends theParent {
}

这是OOP的一个很好的例子。

答案 2 :(得分:0)

你所做的事情被称为覆盖,它没有什么不好但是如果你想让子类更好地坚持父母的签名你使用下面的接口你应该只提供签名和子类mut实现它们因为他们被宣布。

 interface theParent {
      function myMethod($param1) ;
    }

    class theChild extends theParent {
      function myMethod($param1) {
        // code here
      }
    }

希望有所帮助:)

相关问题