【转】PHP的Trait 特性
生活随笔
收集整理的這篇文章主要介紹了
【转】PHP的Trait 特性
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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使用多個 Trait
在同個 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 : method2Trait 之間的嵌套
同時,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 : method2Trait 的抽象方法(Abstract Method)
我們可以在 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 沖突
多個 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 比較基本的使用了,更詳細的可以參考官方手冊。這里總結下注意的幾 點:
- Trait 會覆蓋調用類繼承的父類方法
- Trait 無法如 Class 一樣使用 new 實例化
- 單個 Trait 可由多個 Trait 組成
- 在單個 Class 中,可以使用多個 Trait
- Trait 支持修飾詞(modifiers),例如 final、static、abstract
- 我們能使用 insteadof 以及 as 操作符解決 Trait 之間的沖突
轉載于:https://www.cnblogs.com/zyf-zhaoyafei/p/5341223.html
總結
以上是生活随笔為你收集整理的【转】PHP的Trait 特性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php中urlencode使用
- 下一篇: mcgs组态软件中字体如果从左到右变化_