首頁  >  文章  >  後端開發  >  PHP實作多繼承的trait語法的介紹(程式碼範例)

PHP實作多繼承的trait語法的介紹(程式碼範例)

不言
不言轉載
2019-03-11 15:04:322112瀏覽

這篇文章帶給大家的內容是關於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;
    }
}
$test = new MyCode();
$test->test();
$test->testTwoDemo();

執行結果:

This is trait two 
This is trait two_1

以上是PHP實作多繼承的trait語法的介紹(程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除