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?
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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With