PHP - override function with different number of parameters

感情迁移 提交于 2019-12-03 23:43:18

问题


I'm extending a class, but in some scenarios I'm overriding a method. Sometimes in 2 parameters, sometimes in 3, sometimes without parameters.

Unfortunately I'm getting a PHP warning.

My minimum verifiable example: 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) );

I'm getting PHP error/warning/info:

How can I prevent errors like this?


回答1:


you can redefine methods easily adding new arguments, it's only needs that the new arguments are optional (have a default value in your signature). See below:

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

class Child extends Parent
{
    protected function test($var1, $var2 = null) {
        echo($var1);
        echo($var1);
    }
}

For more detail, check out the link: http://php.net/manual/en/language.oop5.abstract.php




回答2:


Another solution (a bit "dirtier") is to declare your methods with no argument at all, and in your methods to use the func_get_args() function to retrieve your arguments...

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




回答3:


Your interface/abstract class or the most parent class, should cotantin the maximum number of params a method could recieve, you can declare them explicitely to NULL, so if they are not given, no error will occur i.e.

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);

In this case, using the method smth() as an object of 'A' you will be obligated to use only one param ($param1), but using the same method as object 'B' you will be oblgiated to use 2 params ($param1, $param2) and instanciating it from C you have to give all the params



来源:https://stackoverflow.com/questions/16017053/php-override-function-with-different-number-of-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!