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 } }
idmadj
source share