PHP multiple inheritance
Posted: Thu Feb 14, 2008 12:43 am
Hello, I really need to use multiple inheritance, but it's not supported in PHP, is there a way to mimic the concept of multiple inheritance ? Thank you.
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
what arborint said + I really doubt you need itkeenlearner wrote:Hello, I really need to use multiple inheritance, but it's not supported in PHP, is there a way to mimic the concept of multiple inheritance ? Thank you.
Code: Select all
class MixinClass {
private $_mixins = array();
public function setMixins($mixins) {
$this->_mixins = $mixins;
}
public function __call($method, $args) {
foreach ($this->_mixins as $mixin) {
if (method_exists($mixin, $method)) {
return call_user_func_array(array($mixin, $method), $args);
}
}
//otherwise not found
throw new Exception('No such method');
}
public function __get($prop) {
foreach ($this->_mixins as $mixin) {
if (property_exists($mixin, $prop)) {
return $mxin->$prop;
}
}
throw new Exception('No such property');
}
public function __set($prop, $value) {
foreach ($this->_mixins as $mixin) {
if (property_exists($mixin, $prop)) {
$mixin->$prop = $value;
return;
}
}
//Otherwise behave as PHP usually would and set it
$this->$prop = $value;
}
}
class A {
public $foo = 'bar';
public function aMethod($param) {
echo 'aMethod() called with ' . $param;
}
}
class B {
public function bMethod() {
echo 'bMethod() called';
}
}
$mixin = new MixinClass();
$mixin->setMixins(new A(), new B());
$mixin->aMethod('test'); //aMethod() called with test
$mixin->bMethod(); //bMethod() called
echo $mixin->foo; //bar
$mixin->foo = 'test';
echo $mixin->foo; //test
$mixin->meh = 'bleh';
echo $mxin->meh; //bleh