Starx Starx - 1 year ago 53
PHP Question

Is there any way to achieve multiple inheritance in php?

Lets say I have a parent class

class parent { }


This parent has three sub class

class child1 { }

class child2 { }

class child3 { }

and these child classes have further smaller parts like

class child1subpar1 { }

class child1subpar2 {

public function foo() {
echo "hi";


class child2subpar1 { }

class child2subpar2 { }

Now, how to sum this whole up like

class child1 extends child1subpar1, child1subpar2 { }
class child2 extends child2subpar1, childsubpar1 { }

class parent extends child1,child2,child3 { }

I need to execute the methods in its inherited classes and do something like this

$objparent = new parent;
$objparent -> foo();

Answer Source

No, but multiple inheritance is generally considered a bad practice. You should favor composition instead, so you just use instances of classes you wanted to inherit inside your class.

And now when I look into your question again, it's not even an inheritance issue, you should use composition. Maybe if you provided more detail what you expect that class to do, we should answer more accurately.


You will need to create one method for each of these classes' method which you would want to use - it's called Facade design pattern. Or maybe you are not aware that you can call methods of inner objects like this:


Facade pattern:

in your case facade wouldn't be anything else than creating one class and define every single method you want to use, and inside that method calling any method of any of your inner instances. But i really don't see any benefit coming from this instead of calling instances and methods hierarchically