PHP - override function with different number of parameters

。_饼干妹妹 提交于 2019-12-01 02:45:56

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

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

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

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