轉自: https://www.jianshu.com/p/fc053b2d7fd1php
php從之前到如今一直都是單繼承的語言,沒法同時從兩個基類中繼承屬性和方法,爲了解決這個問題,php出了Trait這個特性(據說這個Trait和Go語言有點相似,具體沒學過Go語言)測試
用法:經過在類中使用use 關鍵字,聲明要組合的Trait名稱,具體的Trait的聲明使用Trait關鍵詞,Trait不能實例化spa
以下代碼實例:3d
<?php trait Dog{ public $name="dog"; public function bark(){ echo "This is dog"; } } class Animal{ public function eat(){ echo "This is animal eat"; } } class Cat extends Animal{ use Dog; public function drive(){ echo "This is cat drive"; } } $cat = new Cat(); $cat->drive(); echo "<br/>"; $cat->eat(); echo "<br/>"; $cat->bark(); ?>
將會以下輸出code
<?php trait Dog{ public $name="dog"; public function drive(){ echo "This is dog drive"; } public function eat(){ echo "This is dog eat"; } } class Animal{ public function drive(){ echo "This is animal drive"; } public function eat(){ echo "This is animal eat"; } } class Cat extends Animal{ use Dog; public function drive(){ echo "This is cat drive"; } } $cat = new Cat(); $cat->drive(); echo "<br/>"; $cat->eat(); ?>
以下顯示orm
因此:Trait中的方法或屬性會覆蓋 基類中的同名的方法或屬性,而本類會覆蓋Trait中同名的屬性或方法xml
use trait1,trait2blog
當不一樣的trait中,卻有着同名的方法或屬性,會產生衝突,可使用insteadof或 as進行解決,insteadof 是進行替代,而as是給它取別名
以下實例:繼承
<?php trait trait1{ public function eat(){ echo "This is trait1 eat"; } public function drive(){ echo "This is trait1 drive"; } } trait trait2{ public function eat(){ echo "This is trait2 eat"; } public function drive(){ echo "This is trait2 drive"; } } class cat{ use trait1,trait2{ trait1::eat insteadof trait2; trait1::drive insteadof trait2; } } class dog{ use trait1,trait2{ trait1::eat insteadof trait2; trait1::drive insteadof trait2; trait2::eat as eaten; trait2::drive as driven; } } $cat = new cat(); $cat->eat(); echo "<br/>"; $cat->drive(); echo "<br/>"; echo "<br/>"; echo "<br/>"; $dog = new dog(); $dog->eat(); echo "<br/>"; $dog->drive(); echo "<br/>"; $dog->eaten(); echo "<br/>"; $dog->driven(); ?>
輸出以下get
<?php trait Animal{ public function eat(){ echo "This is Animal eat"; } } class Dog{ use Animal{ eat as protected; } } class Cat{ use Animal{ Animal::eat as private eaten; } } $dog = new Dog(); $dog->eat();//報錯,由於已經把eat改爲了保護 $cat = new Cat(); $cat->eat();//正常運行,不會修改原先的訪問控制 $cat->eaten();//報錯,已經改爲了私有的訪問控制 ?>
<?php trait Cat{ public function eat(){ echo "This is Cat eat"; } } trait Dog{ use Cat; public function drive(){ echo "This is Dog drive"; } abstract public function getName(); public function test(){ static $num=0; $num++; echo $num; } public static function say(){ echo "This is Dog say"; } } class animal{ use Dog; public function getName(){ echo "This is animal name"; } } $animal = new animal(); $animal->getName(); echo "<br/>"; $animal->eat(); echo "<br/>"; $animal->drive(); echo "<br/>"; $animal::say(); echo "<br/>"; $animal->test(); echo "<br/>"; $animal->test(); ?>
輸出以下