PHP實現多繼承 trait 語法


原文地址:http://small.aiweimeng.top/index.php/archives/50.html

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;
    }

}


$test = new MyCode();
$test->test();
$test->testTwoDemo();

  

運行結果:

This is trait two 
This is trait two_1

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM