#PHP 类的多继承实现之 traits.md

TRAIT

PHP本身是并不支持多继承的,也就是,一个类只能继承一个类,为了满足业务需求,后来有了一些解决方法,例如,链式继承,B继承A,然后C继承B,这样,C就同时继承了AB, 此外还有接口,因为接口其实和抽象类很像,同一个类可以实现多个接口,利用接口的此特性,我们也能实现多继承。

但是,自 PHP 5.4.0 起,PHP 实现了代码复用的一个方法,称为 Traits,它能够帮我们更加便捷的实现类的多继承。

实例1

<?php
trait A{
	public function testA(){
		echo "<br>";
		echo "testA call";
	}
}
trait B{
	public function testB(){
		echo "<br>";		
		echo "testB call";
	}
}
trait C{
	public function testC(){
		echo "<br>";		
		echo "testC call";
	}
}
class D{
	use A,B,C;
}

$cls = new D();
$cls->testA();
$cls->testB();
$cls->testC();
?>
#输出

testA call
testB call
testC call

实例2

<?php
class E{
	public function testE(){
		echo "<br>";
		echo "testE call";
	}
}
trait F{
	public function testF(){
		echo "<br>";
		echo "testF call";
	}	
}
class G extends E{
	use F;
}
$cls = new G();
$cls->testE();
$cls->testF();
?>
#输出

testE call
testF call

实例3

<?php
class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}
 
trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}
 
class MyHelloWorld extends Base {
    use SayWorld;
}
 
$o = new MyHelloWorld();
$o->sayHello();
?>

以上例程会输出:

Hello World!

 trait 有一个魔术常量,__TRAIT__,用于在相应trait中打印当前trait的名称。

原文地址:https://www.cnblogs.com/jaycethanks/p/13175091.html