Here's fun, an attempt to make some degree of multiple inheritance work in PHP using mixins. It's not particularly pretty, doesn't support method visibility modifiers and, if put to any meaningful purpose, could well make your call stack balloon to Ruby-on-Rails-esque proportions, but it does work.
<?php
abstract class Mix {
protected $_mixMap = array();
public function __construct(){
$this->_mixMap = $this->collectMixins($this);
}
public function __call($method, $args){
$payload = $this->buildMixinPayload($this->_mixMap, $method, $args);
if(!$payload) throw new Exception('Method ' . $method . ' not found');
list($mixinMethod, list($method, $args)) = $payload;
return $this->$mixinMethod($method, $args);
}
protected function collectMixins($class){
static $found = array();
static $branch = array();
if(empty($branch)) $branch[] = get_class($this);
$mixins = array();
foreach(array_reverse(get_class_methods($class)) as $method){
if(preg_match('/^mixin(\w+)$/', $method, $matches)){
$className = $matches[1];
if(in_array($className, $branch))
throw new Exception('Circular reference detected ' . implode(' > ', $branch) . ' > ' . $className);
if(!in_array($className, $found)){
if(!class_exists($className)) throw new Exception('Class ' . $className . ' not found');
foreach(get_class_vars($className) as $key => $value){
if(!property_exists($this, $key)) $this->$key = $value;
}
$found[] = $branch[] = $className;
$mixins[$className] = $this->collectMixins($className);
}
$branch = array(get_class($this));
}
}
return $mixins;
}
protected function buildMixinPayload($mixins, $method, $args){
foreach($mixins as $className => $parents){
$mixinMethod = 'mixin' . $className;
if(method_exists($className, $method)) return array($mixinMethod, array($method, $args));
if(!empty($parents) && $return = $this->buildMixinPayload($parents, $method, $args)){
return array($mixinMethod, $return);
}
}
return false;
}
}
?>