php實現多繼承-trait語法

轉自:https://www.cnblogs.com/ddddemo/p/6547688.html

自 PHP 5.4.0 起,PHP 實現了一種代碼複用的方法,稱爲 trait。

Trait 是爲類似 PHP 的單繼承語言而準備的一種代碼複用機制。Trait 爲了減少單繼承語言的限制,使開發人員能夠自由地在不同層次結構內獨立的類中複用 method。Trait 和 Class 組合的語義定義了一種減少複雜性的方式,避免傳統多繼承和 Mixin 類相關典型問題。

Trait 和 Class 相似,但僅僅旨在用細粒度和一致的方式來組合功能。 無法通過 trait 自身來實例化。它爲傳統繼承增加了水平特性的組合;也就是說,應用的幾個 Class 之間不需要繼承。

從基類繼承的成員會被 trait 插入的成員所覆蓋。優先順序是來自當前類的成員覆蓋了 trait 的方法,而 trait 則覆蓋了被繼承的方法。

以下爲代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

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

  輸出爲:

1

2

3

This is trait one

one

two

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

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

是致命錯誤。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章