我正在扩展一个类,但在某些情况下我正在覆盖一个方法。有时有 2 个参数,有时有 3 个参数,有时没有参数。
不幸的是,我收到了 PHP 警告。
我的最小可验证示例: http://pastebin.com/6MqUX9Ui
<?php
class first {
public function something($param1) {
return 'first-'.$param1;
}
}
class second extends first {
public function something($param1, $param2) {
return 'second params=('.$param1.','.$param2.')';
}
}
// Strict standards: Declaration of second::something() should be compatible with that of first::something() in /home/szymon/webs/wildcard/www/source/public/override.php on line 13
$myClass = new Second();
var_dump( $myClass->something(123,456) );
我收到 PHP 错误/警告/信息:
我怎样才能避免这样的错误?
最佳答案
您可以轻松地重新定义方法添加新参数,只需要新参数是可选的(在您的签名中有一个默认值)。见下文:
class Parent
{
protected function test($var1) {
echo($var1);
}
}
class Child extends Parent
{
protected function test($var1, $var2 = null) {
echo($var1);
echo($var1);
}
}
有关更多详细信息,请查看链接:http://php.net/manual/en/language.oop5.abstract.php
关于PHP - 用不同数量的参数覆盖函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16017053/