Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic parameters in abstract methods in php

If I have a class,

abstract class Parent {
    abstract function foo();
}

class Child extends Parent {
    function foo($param) {
        //stuff
    }
}

I get an error because the abstract declaration doesn't have any parameters but the child's implementation of it does. I am making an adapter parent class with abstract functions that, when implemented, could have a variable amount of parameters depending on the context of the child class. Is there any structured way I can overcome this, or do I have to use func_get_args?

like image 403
tipu Avatar asked Nov 01 '11 19:11

tipu


2 Answers

PHP does this to protect polymorphism. Any object of the inherited type should be usable as if they were of the parent type.

Consider the following classes:

abstract class Animal {
    abstract function run();
}

class Chicken extends Animal {
    function run() {
        // Clever code that makes a chicken run
    }
}

class Horse extends Animal {
    function run($speed) {
        // Clever code that makes a horse run at a specific speed
    }
}

... and the following code:

function makeAnimalRun($animal) {
    $animal->run();
}

$someChicken = new Chicken();
$someHorse = new Horse();

makeAnimalRun($someChicken);  // Works fine
makeAnimalRun($someHorse);   // Will fail because Horse->run() requires a $speed 

makeAnimalRun should be able to execute run on any instance of Animal's inherited classes, but since Horse's implementation of run requires a $speed parameter, the $animal->run() call in makeAnimalRun fails.

Fortunately, there's an easy fix to this. You just need to provide a default value to the parameter in the overridden method.

class Horse extends Animal {
    function run($speed = 5) {
        // Clever code that makes that horse run at a specific speed
    }
}
like image 196
idmadj Avatar answered Sep 28 '22 01:09

idmadj


You have to use func_get_args if you want to have variable arguments in your function. Note that func_get_args gets all the arguments passed to a PHP function.

You can however enforce a minimum number of arguments to be passed to the function by including corresponding parameters to them.

For example: Say that you have a function that you wish to call with at least 1 argument. Then just write the following:

function foo($param) {
    //stuff
    $arg_list = func_get_args();
}

Now that you have this definition of foo(), you have to at least call it with one argument. You can also choose to pass a variable number of arguments n where n > 1, and receive those arguments through func_get_args(). Keep in mind that $arg_list above will also contain a copy of $param as its first element.

like image 36
Zaki Saadeh Avatar answered Sep 28 '22 00:09

Zaki Saadeh