PHP中的多重继承模拟,如何优化代码

时间:2014-07-09 08:36:56

标签: php class multiple-inheritance extend

我有两个A和B类.C类可能是A和B的扩展。我需要做到最佳。

 class  A { 
    public function testA() { 
      echo "this is function testA \n";
    }
 } 

 class  B { 
    public function testB() { 
       echo "this is function testB \n";
    } 
 }

class C extends A {
   public  function __call($method, $args){
      $this->b =new B();
      try {
         return !method_exists ($this->b , $method ) || !$this->b->$method($args[0]);
      } catch(Exception $e) {
          echo "error";
      }
   }  
}

$object = new C();
$object->testA();
$object->testB();
$object->testD();

如何优化此代码?

1 个答案:

答案 0 :(得分:0)

PHP中的多个“继承”由Traits处理,从5.4.0开始提供 更多信息:http://php.net/manual/en/language.oop5.traits.php     

trait  A { 
    public function testA() { 
      echo "this is function testA \n";
    }
 } 

 trait  B { 
    public function testB() { 
       echo "this is function testB \n";
    } 
 }

class C {
    use A, B;
    public  function __call($method, $args){
        // Called method does not exists.
    }  
}