Question

Assuming I have 2 classes

Class A {
    public function doA(){
        echo "Im A";
    }
}
Class B {
    public function doB(){
        echo "Im B";
    }
}

write Class C, in order that the following code runs:

  $c = new C();
  $c->doA();
  $c->doB();

and outputs:

>> Im A
>> Im B

This was in a test, and the conditions where:

  • use no static calls
  • you can't modify class A or class B

so I wrote:

Class C {

       public function doA() {
             $a = new A();
             $a->doA();
       }

       public function doB() {
             $b = new B();
             $b->doB();
       }

  }

So apparently I was wrong as it can be "more optimized"

can someone tell me how to do it?

Was it helpful?

Solution

You could keep instances of A and B instead of instantiating them each time.

class C {
       private $a, $b;

       public __construct() {
             $this->a = new A();
             $this->b = new B();
       }

       public function doA() {
             $this->a->doA();
       }

       public function doB() {
             $this->b->doB();
       }
}

OTHER TIPS

PHP has no "native" multiple inheritance, but you can achieve something similar to it by using traits.

Trait A {
    public function doA(){
        echo "Im A";
    }
}

Trait B {
    public function doB(){
        echo "Im B";
    }
}

Class C {
    use A, B;
}

$c = new C;
$c->doA();
$c->doB();

Note that this would require at least PHP 5.4.

To do it without modifying classes, the best and optimised option would be as follows.

class C {
    private $a;
    private $b;

    public __construct() {
        $this->a = new A();
        $this->b = new B();
    }

    public function __call($method, $arguments = array()) {
        if(method_exists($this->as, $method)) {
            return call_user_func(array($this->a, $method));
        }
    }
}

The above is also future proof, so adding new methods would also follow.

While you were told not to modify classes A and B, the correct way to do this would be by having B extend A, then having C extend B, like below.

class A {
    public function doA(){
        echo "Im A";
    }
}
class B extends A {
    public function doB(){
        echo "Im B";
    }
}
class C extends B {

}

$c = new C();
$c->doA();
$c->doB();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top