dynamic parameters in abstract methods in php dynamic parameters in abstract methods in php php php

dynamic parameters in abstract methods in php


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 finemakeAnimalRun($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    }}


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.