Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - override function with different number of parameters

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: error screen

How can I prevent errors like this?

like image 995
BlueMan Avatar asked Apr 15 '13 13:04

BlueMan


People also ask

Can I override with different parameters?

No, while overriding a method of the super class we need to make sure that both methods have same name, same parameters and, same return type else they both will be treated as different methods.

Can you override a function in PHP?

Introduction to the PHP overriding methodTo override a method, you redefine that method in the child class with the same name, parameters, and return type. The method in the parent class is called overridden method, while the method in the child class is known as the overriding method.

Can we override properties in PHP?

Is it possible to override parent class property from child class? Yes.

Can we have two functions with the same name in PHP?

Note: PHP's interpretation of overloading is different than most object-oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.


2 Answers

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

like image 139
jose.serapicos Avatar answered Sep 20 '22 19:09

jose.serapicos


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

like image 2
Damien Legros Avatar answered Sep 19 '22 19:09

Damien Legros