php實現多繼承-trait文法

來源:互聯網
上載者:User

標籤:報錯   覆蓋   bsp   fat   extend   line   應用   執行個體化   test   

自 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();

  輸出為:

This is trait oneonetwo

  注意。如果把注釋一行的注釋取消,將會報錯

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

是致命錯誤。

 

php實現多繼承-trait文法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.