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

Blu*_*Man 16 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) );
Run Code Online (Sandbox Code Playgroud)

我收到PHP错误/警告/信息: 错误屏幕

我怎样才能防止这样的错误?

jos*_*cos 23

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

class Parent
{
    protected function test($var1) {
        echo($var1);
    }
}

class Child extends Parent
{
    protected function test($var1, $var2 = null) {
        echo($var1);
        echo($var1);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看链接:http://php.net/manual/en/language.oop5.abstract.php


Roy*_* Bg -1

你的接口/抽象类或者最父类,应该包含一个方法可以接收的最大参数数量,你可以将它们显式声明为NULL,所以如果没有给出,不会发生错误,即

Class A{
public function smth($param1, $param2='', $param3='')

Class B extends A {
public function smth($param1, $param2, $param3='')

Class C extends B {
public function smth($param1, $param2, $param3);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,使用方法 smth() 作为“A”的对象,您将不得不仅使用一个参数($param1),但使用与对象“B”相同的方法,您将不得不使用 2 个参数( $param1, $param2) 并从 C 实例化它,你必须给出所有参数