PHP的Trait機制原理與用法分析
本文實例講述了PHP的Trait機制原理與用法。分享給大家供大家參考,具體如下:
Trait介紹:
1、自PHP5.4起,PHP實現(xiàn)了一種代碼復用的方法,稱為trait。
2、Trait是為類似PHP的單繼承語言二準備的一種代碼復用機制。
3、Trait為了減少單繼承語言的限制,使開發(fā)人員能夠自由地在不同層次結構內(nèi)獨立的類中復用method。
4、trait實現(xiàn)了代碼的復用,突破了單繼承的限制;
5、trait是類,但是不能實例化。
6、當類中方法重名時,優(yōu)先級,當前類>trait>父類;
7、當多個trait類的方法重名時,需要指定訪問哪一個,給其它的方法起別名。
示例:
trait Demo1{ public function hello1(){ return __METHOD__; } } trait Demo2{ public function hello2(){ return __METHOD__; } } class Demo{ use Demo1,Demo2;//繼承Demo1和Demo2 public function hello(){ return __METHOD__; } public function test1(){ //調(diào)用Demo1的方法 return $this->hello1(); } public function test2(){ //調(diào)用Demo2的方法 return $this->hello2(); } } $cls = new Demo(); echo $cls->hello(); echo "
"; echo $cls->test1(); echo "
"; echo $cls->test2();
運行結果:
Demo::hello
Demo1::hello1
Demo2::hello2
多個trait方法重名:
trait Demo1{ public function test(){ return __METHOD__; } } trait Demo2{ public function test(){ return __METHOD__; } } class Demo{ use Demo1,Demo2{ //Demo1的hello替換Demo2的hello方法 Demo1::test insteadof Demo2; //Demo2的hello起別名 Demo2::test as Demo2test; } public function test1(){ //調(diào)用Demo1的方法 return $this->test(); } public function test2(){ //調(diào)用Demo2的方法 return $this->Demo2test(); } } $cls = new Demo(); echo $cls->test1(); echo "
"; echo $cls->test2();
運行結果:
Demo1::test
Demo2::test
更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
PHP中include/require/include_once/require_once使用心得
include() 、require()語句包含并運行指定文件。這兩結構在包含文件上完全一樣,唯一的區(qū)別是對于錯誤的處理。require()語句在遇到包含文件不存在,或是出錯的時候,就停止即行,并報錯。include()則繼續(xù)即行。2016-08-08PHP中用接口、抽象類、普通基類實現(xiàn)“面向接口編程”與“耦合方法”簡述
邊學邊做的,為方便自己翻閱而發(fā)布,更為得到高人指點而發(fā)布,歡迎高手指點2011-03-03PHP實現(xiàn)將textarea的值根據(jù)回車換行拆分至數(shù)組
這篇文章主要介紹了PHP實現(xiàn)將textarea的值根據(jù)回車換行拆分至數(shù)組,涉及表單元素及explode拆分字符串的相關技巧,需要的朋友可以參考下2015-06-06