本篇文章給大家帶來的內容是關于PHP實現多繼承的trait語法的介紹(代碼示例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
PHP沒有多繼承的特性。即使是一門支持多繼承的編程語言,我們也很少會使用這個特性。在大多數人看來,多繼承不是一種好的設計方法。
但是開發中用到多繼承該怎么辦呢?
下面介紹一下使用"trait"來實現php中多繼承的問題。
自PHP5.4開始,php實現了代碼復用的方法"trait"語法。
Trait是為PHP的單繼承語言而準備的一種代碼復用機制。為了減少單繼承的限制,是開發在不同結構層次上去復用method,Trait 和 Class 組合的語義定義了一種減少復雜性的方式,避免傳統多繼承和 Mixin 類相關典型問題。
需要注意的是,從基類繼承的成員會被 trait 插入的成員所覆蓋。優先順序是來自當前類的成員覆蓋了 trait 的方法,而 trait 則覆蓋了被繼承的方法。
先來個例子:
- trait TestOne{
- public function test()
- {
- echo "This is trait one <br/>";
- }
- }
- trait TestTwo{
- public function test()
- {
- echo "This is trait two <br/>";
- }
- public function testTwoDemo()
- {
- echo "This is trait two_1";
- }
- }
- class BasicTest{
- public function test(){
- echo "hello world/n";
- }
- }
- class MyCode extends BasicTest{
- //如果單純的直接引入,兩個類中出現相同的方法php會報出錯
- //Trait method test has not been applied, because there are collisions with other trait
- //methods on MyCode
- //use TestOne,TestTwo;
- //怎么處理上面所出現的錯誤呢,我們只需使用insteadof關鍵字來解決方法的沖突
- use TestOne,TestTwo{
- TestTwo::test insteadof TestOne;
- }
- //Vevb.com
- }
- $test = new MyCode();
- $test->test();
- $test->testTwoDemo();
運行結果:
This is trait two
This is trait two_1
以上就是PHP實現多繼承的trait語法的介紹(代碼示例)的詳細內容。
新聞熱點
疑難解答