0

Suppose I have the following :

<?php
class Final extends Intermediate {
  public function final_level() {
      $this->low_level();
      $this->inter_level();
  }
}

class Intermediate extends Lib1 {
  public function inter_level() {
      $this->low_level();
  }
}

class Lib1 {
  public function low_level1();
  public function low_level2();
}

class Lib2 {
  public function low_level1();
  public function low_level2();
}

I would like to change the Intermediate class to extend Lib1 or Lib2, depending on some conditions, without duplicating Intermediate and Final code content.

All low_level functions are the same for both Lib.

In the end, I would like to have a Final1 class that use Lib1 (and Final2 that use Lib2).

How could I achieve this ?

1 Answer 1

3

You cannot achieve this via inheritance but you can via delegation

With this approach you delegate the implementation of some methods to a 'delegate' object rather than a base class.

Here it is an example:

<?php
class Final extends Intermediate {
  public function __construct(Lib delegate) {
      parent::__construct(delegate);
  }
  public function final_level() {
      $this->low_level();
      $this->inter_level();
  }
}

class Intermediate implements Lib { //here you implement an interface rather than extending a class

  private Lib delegate;
  public function __construct(Lib delegate) {
      $this->delegate = delegate;
  }
  public function inter_level() {
      $this->low_level();
  }

  public function low_level() {
       //delegate!
       $this->delegate->low_level();
  }
}

class Lib1 implements Lib{
  public function low_level(); //implementation #1
}

class Lib2 implements Lib {
  public function low_level(); //implementation #2
}

interface Lib {
  public function low_level();
}

now you can create your final1 and final2 object in this way:

 $final1 = new Final(new Lib1());
 $final2 = new Final(new Lib2());

or, if you prefer, you can create the Final1 and Final2 classes extending from Final:

  class Final1 extends Final {
       public function __construct()
       {
           parent::__construct(new Lib1());
       }
  }

  class Final2 extends Final {
       public function __construct()
       {
           parent::__construct(new Lib2());
       }
  }

  $final1 = new Final1();
  $final2 = new Final2(); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.