Multiple Inheritance in PHP
With the magic of __call() it is possible to do multiple inheritance in PHP. This example is more then a mixin pattern. It can also call protected and private methods from inherited classes.
<?php
abstract class Inheritance {
private $_inheritances = array();
public function __call($method, array $arguments = array()) {
// Here you can handle the calls. Maybe you don't want to call
// every found method but only the first or the last ...
foreach ($this->_inheritances as $inheritance) {
$inheritance->invoke($method, $arguments);
}
}
public function invoke($method, $arguments) {
if (method_exists($this, $method) === true) {
return call_user_func_array(array($this, $method), $arguments);
}
}
protected function _addInheritance(Inheritance $inheritance) {
$this->_inheritances[get_class($inheritance)] = $inheritance;
}
}
That’s all! Now the usage:
We have two simple base classes, Bird and Horse, which have some methods.
/**
* first base class
*/
class Bird extends Inheritance {
public function chirp() {
echo "<br/>chirp ..";
}
public function fly() {
echo "<br/>fly ..";
}
protected function _eat() {
echo "<br/>eat worms ..";
}
}
/**
* second base class
*/
class Horse extends Inheritance {
public function whinny() {
echo "<br/>whinny ..";
}
protected function _eat() {
echo "<br/>eat hay ..";
}
}
Now we want a new class named Pegasus that implements all methods from Bird and Horse. The only thing we have to do is to inherit from Inheritance and add the two base classes with _addInheritance().
class Pegasus extends Inheritance {
public function __construct() {
// bind extented classes
$this->_addInheritance(new Bird);
$this->_addInheritance(new Horse);
}
public function eat() {
// works with protected methods, too
$this->_eat();
}
}
$pegasus = new Pegasus;
$pegasus->chirp();
$pegasus->fly();
$pegasus->whinny();
$pegasus->eat();
Output:
chirp .. fly .. whinny .. eat worms .. eat hay ..
Kategorienphp