a mechanism for code reuse in single inheritance languages

php.net

 

 1 <?php
 2 class Base {
 3     public function sayHello() {
 4         echo 'Hello';
 5     }
 6 }
 7 
 8 trait SayWorld {
 9     public function sayHello() {
10         parent :: sayHello();
11         echo 'World!';
12     }
13 }
14 
15 class MyHelloWorld extends Base {
16     use SayWorld;
17 }
18 
19 $o = new MyHelloWorld();
20 $o->sayHello();
21 
22 
23 
24 trait HelloWorld {
25     public function sayHello() {
26         echo 'Hello World';
27     }
28 }
29 class TheWorldIsNotEnough {
30     use HelloWorld;
31     public function sayHello() {
32         echo 'Hello Universe!';
33     }
34 }
35 
36 $ob = new TheWorldIsNotEnough();
37 $ob->sayHello();
38 
39 trait Hello {
40     public function sayHello() {
41         echo 'Hello';
42     }
43 }
44 
45 trait World {
46     public function sayWorld() {
47         echo 'World';
48     }
49 }
50 
51 class MyHelloWorld_c {
52     use Hello, World;
53     public function sayExclamationMark() {
54         echo '!';
55     }
56 }
57 
58 $oc = new MyHelloWorld_c();
59 $oc->sayHello();
60 $oc->sayWorld();
61 $oc->sayExclamationMark();

Precedence
An inherited member from a base class is overridden by a member inserted  by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.   

The precedence order is that methods from the current class override Trait methods, which in turn override methods from the base class.

 

A Trait is similar to a class, but only intended to group functionality in a  fine-grained and consistent way. It is not possible to instantiate a Trait on  its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

posted @ 2016-08-16 23:30  papering  阅读(209)  评论(0编辑  收藏  举报