【问题标题】:PHP Class inheritancePHP 类继承
【发布时间】:2021-09-17 13:31:53
【问题描述】:

假设我有以下:

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

我想根据某些条件更改Intermediate类以扩展Lib1或Lib2,而不重复Intermediate和Final代码内容。

两个 Lib 的所有低级函数都是相同的。

最后,我想要一个使用 Lib1 的 Final1 类(以及使用 Lib2 的 Final2)。

我怎样才能做到这一点?

【问题讨论】:

    标签: php design-patterns


    【解决方案1】:

    你不能通过继承来实现这一点,但你可以通过委托

    使用这种方法,您可以将某些方法的实现委托给“委托”对象而不是基类。

    这是一个例子:

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

    现在您可以通过这种方式创建您的 final1 和 final2 对象:

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

    或者,如果您愿意,可以创建从 Final 扩展而来的 Final1 和 Final2 类:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 2015-08-28
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多