添加参数覆盖方法E_STRICT观察 [英] adding parameters to overriden method E_STRICT observation
问题描述
出现(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?
推荐答案
如果您添加了非默认参数, -defaulted参数到重写的方法,子类不再满足超类定义的契约。你不能正确地调用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屋!