PHP multiple inheritance
Moderator: General Moderators
-
keenlearner
- Forum Commoner
- Posts: 50
- Joined: Sun Dec 03, 2006 7:19 am
PHP multiple inheritance
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.
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: PHP multiple inheritance
Inheritance is often replaced with composition these days and you can obviously do multiple-composition. And, PHP does support multiple interface inheritance which is a solution to some problems.
(#10850)
Re: PHP multiple inheritance
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.
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Re: PHP multiple inheritance
Please don't shoot me
But dare I say it? Mixins.
EDIT | Just t be 100% blunt on something however, mixins do not behave as if they are all inheriting from one another... it's more of a voodoo composition technique which allow you to call methods on inner objects using the front-facing interface.
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