lanying56123 发表于 2017-12-30 14:01:28

php实现多继承

  自 PHP 5.4.0 起,PHP 实现了一种代码复用的方法,称为 trait。

  Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和>
  Trait 和>  从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法。
  以下为代码:
  

trait traitTestOne{  public function test(){
  echo "This is trait one <br/>";
  }
  public function testOne(){
  echo "one <br/>";
  }
  
}
  

  
trait traitTestTwo{
  
// public function test(){
  
// echo "This is trait two";
  
// }
  public function testTwo(){
  echo "two <br/>";
  }
  
}
  

  
class basicTest{
  public function test(){
  echo "hello world\n";
  }
  
}
  
class myCode extends basicTest{
  use traitTestOne,traitTestTwo;
  
}
  

  
$test = new mycode();
  
$test->test();
  
$test->testOne();
  
$test->testTwo();
  

  

  输出为:
  

This is trait one  
one
  
two
  

  

  注意。如果把注释一行的注释取消,将会报错
  Fatal error: Trait method test has not been applied, because there are collisions with other trait methods on myCode in ......test.php on line 28
  是致命错误。
页: [1]
查看完整版本: php实现多继承