首页 > 其他 > 详细

a mechanism for code reuse in single inheritance languages

时间:2016-08-17 01:18:17      阅读:169      评论:0      收藏:0      [点我收藏+]

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.

a mechanism for code reuse in single inheritance languages

原文:http://www.cnblogs.com/yuanjiangw/p/5778288.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!