PHP - 用不同数量的参数覆盖函数

标签 php oop overriding

我正在扩展一个类,但在某些情况下我正在覆盖一个方法。有时有 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

我怎样才能避免这样的错误?

最佳答案

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

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/

相关文章:

php - 从扩展模板调用时的 $smarty.current_dir 值

java - 下面的OOP设计有更好的替代方案吗?

python - 在 Python 内部理解 self

oop - 我们保护我们的类(class)免受谁的侵害?

java - 无法访问数组java中的对象

attributes - Hybris - 覆盖项目类型的现有唯一属性,使它们不唯一

c++ - 用私有(private)基函数覆盖公共(public)虚函数?

php - 如何在单元测试(PHPUnit)中的 trigger_error(..., E_USER_WARNING) 之后执行代码?

php 选择和 json 编码问题

PHP shell_exec 停止工作