自 PHP 5.4.0 起,PHP 實現了一種代碼複用的方法,稱爲 trait。
Trait 是爲類似 PHP 的單繼承語言而準備的一種代碼複用機制。Trait 爲了減少單繼承語言的限制,使開發人員能夠自由地在不同層次結構內獨立的類中複用 method。Trait 和 Class 組合的語義定義了一種減少複雜性的方式,避免傳統多繼承和 Mixin 類相關典型問題。
Trait 和 Class 相似,但僅僅旨在用細粒度和一致的方式來組合功能。 無法通過 trait 自身來實例化。它爲傳統繼承增加了水平特性的組合;也就是說,應用的幾個 Class 之間不需要繼承。
從基類繼承的成員會被 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(); |
輸出爲:
1
2
3
|
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
是致命錯誤。