Can you extend two classes in one class?

Possible duplicate:
Is it possible to extend a class using more than 1 class in PHP?

I have a class that has several child classes, however now I am adding another class that also wants to be a child of the parent, however I would also like to use many functions from one of the other child classes.

I thought of simply moving the corresponding functions from another child class to the parent, but I didn’t think that it was really necessary, since these would be the only two child classes that use them, so I hoped that I could extend from the main parent class and from one from existing child classes.

+7
source share
5 answers

You can extend the child class to inherit both its parent and child functions, which I think you are trying to do.

class Parent { protected function _doStuff(); } class Child extends Parent { protected function _doChildStuff(); } class Your_Class extends Child { // Access to all of Parent and all of Child members } // Your_Class has access to both _doStuff() and _doChildStuff() by inheritance 
+9
source

No php is the only inheritance language. If you can find the upcoming function in php 5.4, these are the traits.

+8
source

As @morphles pointed out, this function will be available as tags (e.g. mixins in other languages) in php 5.4. However, if this is really necessary, you can use a workaround like this:

 // your class #1 class A { function smthA() { echo 'A'; } } // your class #2 class B { function smthB() { echo 'B'; } } // composer class class ComposeAB { // list of implemented classes private $classes = array('A', 'B'); // storage for objects of classes private $objects = array(); // creating all objects function __construct() { foreach($this->classes as $className) $this->objects[] = new $className; } // looking for class method in all the objects function __call($method, $args) { foreach($this->objects as $object) { $callback = array($object, $method); if(is_callable($callback)) return call_user_func_array($callback, $args); } } } $ab = new ComposeAB; $ab->smthA(); $ab->smthB(); 
+8
source

As a yes / no answer, I can say no. You cannot extend to multiple classes in php. but you can use interface instead.

+2
source

You can do this by thinking in the opposite direction, however it depends on the situation. If you want your classes to be separated, no one can give you a good answer on how to structure your objects and inheritance unless you give us more information. Also keep in mind that worrying too much about getting the right class structure is a burden for small projects, and you can simply move these methods and execute them and then learn more about classes later.

0
source

All Articles