Can you extend two classes in one class? [duplicate]

馋奶兔 提交于 2019-12-05 02:12:12

You can extend the child class to inherit both its parent and the child's functions, which I think is what 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's members
}

// Your_Class has access to both _doStuff() and _doChildStuff() by inheritance

As said @morphles, this feature will be available as traits (like mixins in other languages) in php 5.4. However, if it's really needed, you can use such workaround:

// 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();

No php is single inheritance language. If you can you can lookup upcoming feature in php 5.4, that is traits.

As a yes/no answer i can say no. You can't extend from multiple classes in php. but you can use interface instead.

You can do this by thinking backwards, however it depends on the situation. If you would like to keep your classes separate, nobody can give you a good answer of how to structure your objects and inheritance unless you give us more information. Also keep in mind that getting too worried about getting class structure right is a burden in small projects and you may as well just move the methods over and be done with it and learn more about classes later.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!