首页 > Web开发 > 详细

php组合

时间:2016-05-08 11:54:48      阅读:185      评论:0      收藏:0      [点我收藏+]

为了提高代码的复用性,降低代码的耦合(组合实现的两种方式)

模式一:

 1 <?php
 2 //组合模式一
 3 class Person{
 4     public function eat(){
 5         echo "eat.<br/>";
 6     }
 7 }
 8 
 9 class Phone{
10     public function call(){
11         echo "phone call.<br/>";
12     }
13 }
14 
15 //学生也需要call()这个方法,为了提高代码的复用性(组合)
16 class Student extends Person{
17     private $people;
18     public function learning(){
19         echo "learn.<br/>";
20     }
21     public function func($class, $method){//兼容多个类的多个方法
22         $this->people = new $class;
23         $this->people->$method();
24     }
25 }
26 
27 $student = new Student();
28 $student->eat();
29 $student->func(‘Phone‘, ‘call‘);
30 $student->learning();

模式二:

技术分享
 1 <?php
 2 //组合模式二
 3 class Person{
 4     public function eat(){
 5         echo "eat.<br/>";
 6     }
 7 }
 8 
 9 trait Drive{
10     public function call(){
11         echo "phone call.<br/>";
12     }
13 }
14 
15 class Student extends Person{
16     use Drive;
17     public function learning(){
18         echo "learn.<br/>";
19     }
20 }
21 
22 $student = new Student();
23 $student->eat();
24 
25 //当方法或属性同名时,当前类中的方法会覆盖 trait的 方法,而 trait 的方法又覆盖了基类中的方法
26 $student->call();
27 $student->learning();
View Code

 

php组合

原文:http://www.cnblogs.com/573583868wuy/p/5470083.html

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