<?php
/*
?* WEB开发笔记 www.chhua.com 每日练习之PHP使用组合实现类的多态
?*/
/*
?* 类说明:某大学开两门课程,一个是PHP,一个是JAVA,规定不同的价格
?*/
abstract class lesson {//定义一个抽象基类
?protected $lessonType;
?private $selectCost;
?public function __construct($type=1,costClass $costclass){
??$this->lessonType=$type;
??$this->selectCost=$costclass;
?}
?
?public function cost(){//计算学费
??return $this->selectCost->cost();
?}
?
?public function getType(){//返回类型字符串
??????? return $this->selectCost->getType();
?}
}

//======================以下是为lesson基类的__construct 创建 costClass 类型的功能实现参数
abstract class costClass {
??? abstract function cost();
??? abstract function getType();
}

class phpcost extends costClass{
?function cost(){
??return 30;
?}
?function getType(){
??return “Lesson For PHP”;
?}
}

class javacost extends costClass{
?function cost(){
??return 50;
?}
?function getType(){
??return “Lesson For JAVA”;
?}
}

//========================以下是实例化最终对象
class lessonPHP extends lesson{
?public function getFeiyong(){//自己的特性方法
??echo $this->cost();
?}
}

class lessonJAVA extends lesson{
?public function getLessonName(){//自己的特性方法
??echo $this->getType();
?}
}

$phpLesson=new lessonPHP(1,new phpcost());
$javaLesson= new lessonJAVA(2,new javacost());

$phpLesson->getFeiyong();
$javaLesson->getLessonName();

/*
?*注:以上就是通过用PHP组合来实现多态的最简单的例子。各个类之间的功能是独立的,降低耦合
?*
?*/
?>