本文實例講述了PHP Trait功能與用法。分享給大家供大家參考,具體如下:
Trait 是為類似 PHP 的單一繼承語言而準備的一種程式碼重複使用機制。
trait A{ public function eat(){ echo 'A-eat'; } public function say(){ echo 'A-say'; } } trait B{ public function eat(){ echo 'B-eat'; } public function say(){ echo 'B-say'; } } class People{ use A,B{ A::eat insteadof B; B::eat as eatbak; B::say insteadof A; } } $people = new People(); $people->eat(); echo "<br/>"; $people->say(); echo "<br/>"; $people->eatbak();
運行結果:
A-eat
B-say
B-eat
<?php trait Test { public function say() { echo 'say hello'; } } class People { use Test { say as protected; } } $people = new People(); $people->say();
執行結果:
Fatal error: Call to protected method People::say() from context '' in D:\phpdemo\trait_Demo.php on line 14
#相關學習推薦:PHP程式設計從入門到精通
以上是PHP之Trait功能與用法實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!