If I have several classes with functions that I need but want to store separately for organisation, can I extend a class to have both?
i.e. class a extends b extends c
edit: I know how to extend classes one at a time, but I'm looking for a method to instantly extend a class using multiple base classes - AFAIK you can't do this in PHP but there should be ways around it without resorting to class c extends b
, class b extends a
Answering your edit :
If you really want to fake multiple inheritance, you can use the magic function __call().
This is ugly though it works from class A user's point of view :
class B {
public function method_from_b($s) {
echo $s;
}
}
class C {
public function method_from_c($s) {
echo $s;
}
}
class A extends B
{
private $c;
public function __construct()
{
$this->c = new C;
}
// fake "extends C" using magic function
public function __call($method, $args)
{
$this->c->$method($args[0]);
}
}
$a = new A;
$a->method_from_b("abc");
$a->method_from_c("def");
Prints "abcdef"
I actually quite like the idea of extending the class Are there any known limitations of doing it this way?
No limitations as far as I know, PHP is a very permissive language for little hacks like this. :) As others have pointed out, it's not the proper OOP way of doing it though.
You will not be able to use protected or private methods.
@wormhit, though, I wouldn't recommend it for use in production, one can use ReflectionClass to access private and protected methods.
This won't work for Implements, which expects the method to actually exist and the behaviour is pretty much undefined when multiple base classes have a method with the same name. It will also mess up your editor's ability to give you hints.