0

Possible Duplicate:
Is Multiple Inheritance allowed at class level in PHP?

How can i resolve this problem

<?php
class A {
    public function af() {
        print 'a';
    }
    public function bark() {
        print ' arf!';
    }
}

class B {
    public function bf() {
        print 'b';
    }
}

class C extends B, A /*illegal*/ {
    public function cf() {
        print 'c';
    }

    public function bark() {
        print ' ahem...'; 
        parent::bark();
    }
}
    
$c = new C; 
$c->af(); 
$c->bf(); 
$c->cf();
print "<br />";
$c->bark();
//Parse Error
?>
Community
  • 1
  • 1

1 Answers1

1

You can't, PHP does not support multiple inheritance. You can make A inherit from B or vice versa; or you can wrap additional instances of A and B within C and proxy method calls to them as needed:

class C {
    protected $a, $b;
    function __construct(A $a, B $b) {
        $this->a = $a;
        $this->b = $b;
    }
    function af() {
        return $this->a->af();
    }
    function bf() {
        return $this->b->bf();
    }
    // ... etc...
}

(Now with dependancy injection to placate OOP purists)

lanzz
  • 42,060
  • 10
  • 89
  • 98
  • Traits are probably a better idea, but I like your idea, – Madara's Ghost Jun 14 '12 at 14:20
  • Traits _are_ a better idea, if you can count on PHP 5.4 being available. – lanzz Jun 14 '12 at 14:22
  • This is actually bad OO as you make an object directly dependant on 2 other objects. You just expect them to be there. Dependancy Injection would be better. @Truth And traits are almost always a sign of bad design. – w00 Jun 14 '12 at 14:24
  • @w00: Psh. You're misunderstanding traits, then -- they have rather little to do with design. They're about *implementation*. They clean up the code. I'd consider them better than having a dozen classes do the same thing in slightly different ways, or having a dozen methods whose sole purpose is to proxy for some private object that actually does the work, or having to put the methods three levels up in the inheritance tree and thus making a dozen other classes inherit the functionality when it doesn't make sense for them. – cHao Jun 14 '12 at 15:54
  • @cHao Psh. No, it's just bad design. Instead of using traits to hack code into a class it is better to pass in the dependencies via the constructor or via setters (through an interface). That way your class isn't hard coupled to a trait. That way you can still adhere to the Open/Close principal (SOLID design). Thus have versioned APIs if needed. But be my guest and use Traits if you think they are any good. – w00 Jun 15 '12 at 12:21