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 paragraph declaration has no parameters, but an implementation of this child. I create a parent adapter class with abstract functions that, when implemented, can have a variable number of parameters depending on the context of the child class. Is there any structured way that I can overcome this, or do I need to use func_get_args?

+8
inheritance php abstract
source share
2 answers

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

However, you can provide a minimum number of arguments that must be passed to the function by including the appropriate parameters in them.

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

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

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

+3
source share

PHP does this to protect polymorphism. Any object of an inherited type must be used as if they were a 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 must run in any instance of the Animal inherited classes, but since the Horse implementation of run requires the $speed parameter, calling $animal->run() on makeAnimalRun fails.

Fortunately, this is easy to fix. You just need to provide the default value for 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 } } 
+12
source share

All Articles