向覆盖的方法E_STRICT观察中添加参数 [英] adding parameters to overridden method E_STRICT observation

查看:101
本文介绍了向覆盖的方法E_STRICT观察中添加参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(PHP 5.3)似乎,如果您要覆盖类方法,则可以这样做,只要它们具有默认值,就可以添加其他参数.

It appears (PHP 5.3) that if you are overriding a class method, it is okay to you can add additional parameters, as long as they have default values.

例如,考虑以下类别:

class test1 {
  public function stuff() {
    echo "Hi";
  }
}

以下类扩展了"test1",并将产生E_STRICT警告.

The following class extends "test1" and will produce an E_STRICT warning.

class test2 extends test1 {
  public function stuff($name) {
    echo "Hi $name";
  }
}

但是,以下内容不会产生E_STRICT警告.

But, the following does not produce an E_STRICT warning.

class test3 extends test1 {
  public function stuff($name = "") {
    echo "Hi $name";
  }
}

虽然类"test3"不会产生E_STRICT警告,但我的印象是PHP不允许重载覆盖方法签名.所以,我不得不问.我的发现是错误/缺陷还是实际上是正确的预期行为?

While class "test3" doesn't produce an E_STRICT warning, I have been under the impression that PHP does not allow method signatures to be overloaded overridden. So, I have to ask. Is my observation a bug/flaw or actually correct intended behavior?

此外,如果默认参数参数可以,为什么非默认参数参数不能?

Further, if a default argument parameter is okay, why is a non-default argument parameter not okay?

推荐答案

如果将非默认参数添加到重写的方法中,则子类将不再满足由超类定义的协定.您无法正确调用test2-> stuff(),因为此方法现在需要一个参数-但超类说您应该能够在没有参数的情况下调用它.因此,出现E_STRICT警告.

If you add a non-defaulted parameter to an overridden method, the subclass no longer satisfies the contract defined by the superclass. You cannot correctly call test2->stuff(), because this method now expects a parameter - but the superclass says you should be able to call it without one. Hence the E_STRICT warning.

但是,如果您添加默认参数,则仍可以按照超类的预期调用test3-> stuff()(来自您的示例),因此合同不会中断.实际上,通过添加可选参数,您只需扩展它即可.

If you add a defaulted parameter though, you can still call test3->stuff() (from your example) - as the superclass expects - and so the contract is not broken. In fact, by adding the optional parameter, you have simply extended it.

这篇关于向覆盖的方法E_STRICT观察中添加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆