Trait是在PHP5.4中加入的,它既不是接口也不是類。主要是為了解決單繼承語言的限制。是PHP多重繼承的一種解決方案。例如,需要同時繼承兩個 Abstract Class, 這將會是件很麻煩的事情,Trait 就是為了解決這個問題。它能被加入到一個或多個已經存在的類中。它聲明了類能做什麼(表明了其接口特性),同時也包含了具體實現(表明了其類特性)
首先,當然是聲明個 Trait,PHP5.4 增加了 trait 關鍵字
1 trait first_trait {
2 function first_method() { /* Code Here */ }
3 function second_method() { /* Code Here */ }
4 }
同時,如果要在 Class 中使用該 Trait,那麼使用 use 關鍵字
1 class first_class {
2 // 注意這行,聲明使用 first_trait
3 use first_trait;
4 }
5
6 $obj = new first_class();
7
8 // Executing the method from trait
9 $obj->first_method(); // valid
10 $obj->second_method(); // valid
在同個 Class 中可以使用多個 Trait
1 trait first_trait
2 {
3 function first_method() { echo "method1"; }
4 }
5
6 trait second_trait {
7 function second_method() { echo "method2"; }
8 }
9
10 class first_class {
11 // now using more than one trait
12 use first_trait, second_trait;
13 }
14
15 $obj= new first_class();
16
17 // Valid
18 $obj->first_method(); // Print : method1
19
20 // Valid
21 $obj->second_method(); // Print : method2
同時,Trait 之間也可以相互的嵌套,例如
1 trait first_trait {
2 function first_method() { echo "method1"; }
3 }
4
5 trait second_trait {
6 use first_trait;
7 function second_method() { echo "method2"; }
8 }
9
10 class first_class {
11 // now using
12 use second_trait;
13 }
14
15 $obj= new first_class();
16
17 // Valid
18 $obj->first_method(); // Print : method1
19
20 // Valid
21 $obj->second_method(); // Print : method2
我們可以在 Trait 中聲明需要實現的抽象方法,這樣能使使用它的 Class 必須實現它
1 trait first_trait {
2 function first_method() { echo "method1"; }
3
4 // 這裡可以加入修飾符,說明調用類必須實現它
5 abstract public function second_method();
6 }
7
8 class first_method {
9 use first_trait;
10
11 function second_method() {
12 /* Code Here */
13 }
14 }
多個 Trait 之間同時使用難免會沖突,這需要我們去解決。PHP5.4 從語法方面帶入了相關 的關鍵字語法:insteadof 以及 as ,用法參見
1 trait first_trait {
2 function first_function() {
3 echo "From First Trait";
4 }
5 }
6
7 trait second_trait {
8 // 這裡的名稱和 first_trait 一樣,會有沖突
9 function first_function() {
10 echo "From Second Trait";
11 }
12 }
13
14 class first_class {
15 use first_trait, second_trait {
16 // 在這裡聲明使用 first_trait 的 first_function 替換
17 // second_trait 中聲明的
18 first_trait::first_function insteadof second_trait;
19 }
20 }
21
22 $obj = new first_class();
23
24 // Output: From First Trait
25 $obj->first_function();
上面就是些 Trait 比較基本的使用了,更詳細的可以參考官方手冊。這裡總結下注意的幾 點:
文章出處:http://www.kuqin.com/web/20111119/315048.html