PHP - 具有不同参数数的覆盖函数

2022-08-30 20:36:57

我正在扩展一个类,但在某些情况下,我正在重写一个方法。有时在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 错误/警告/信息:error screen

如何防止此类错误?


答案 1

您可以轻松地重新定义方法,添加新参数,只需要新参数是可选的(在签名中具有默认值)。见下文:

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


答案 2

另一种解决方案(有点“肮脏”)是声明你的方法,根本没有参数,并在你的方法中使用函数来检索你的参数......func_get_args()

http://www.php.net/manual/en/function.func-get-args.php


推荐