SpiderWan
SpiderWan

Reputation: 966

PHP Class inheritance

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 ?

Upvotes: 0

Views: 76

Answers (1)

ddfra
ddfra

Reputation: 2565

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

Upvotes: 3

Related Questions