在php中不支持多重继承,如果我们向使用多个类的方法而实现代码重用有什么办法么?
那就是组合。在一个类中去将另外一个类设置成属性。
下面的例子,模拟了多重继承。
接口实例
写一个概念性的例子。 我们设计一个在线销售系统,用户部分设计如下: 将用户分为,normaluser, vipuser, inneruser 三种。要求根据用户的不同折扣计算用户购买产品的价格。并要求为以后扩展和维护预留空间。
代码如下:
setname($_name);
}
function getname() {
return $this->name;
}
function setname($_name) {
$this->name = $_name;
}
function getdiscount() {
return $this->discount;
}
function getgrade() {
return $this->grade;
}
}
class normaluser extends abstractuser
{
protected $discount = 1.0;
protected $grade = normal;
}
class vipuser extends abstractuser
{
protected $discount = 0.8;
protected $grade = vipuser;
}
class inneruser extends abstractuser
{
protected $discount = 0.7;
protected $grade = inneruser;
}
interface product
{
function getproductname();
function getproductprice();
}
interface book extends product
{
function getauthor();
}
class bookonline implements book
{
private $productname;
protected $productprice;
protected $author;
function __construct($_bookname) {
$this->productname = $_bookname;
}
function getproductname() {
return $this->productname;
}
function getproductprice() {
$this->productprice = 100;
return $this->productprice;
}
public function getauthor() {
$this->author = chenfei;
return $this->author;
}
}
class productsettle
{
public static function finalprice(user $_user, product $_product, $number) {
$price = $_user->getdiscount() * $_product->getproductprice() * $number;
return $price;
}
}
$number = 10;
$book = new bookonline(设计模式);
$user = new normaluser(tom);
$price = productsettle::finalprice($user, $book, $number);
$str = 您好,尊敬的 . $user->getname() .
;
$str .= 您的级别是 . $user->getgrade() .
;
$str .= 您的折扣是 . $user->getdiscount() .
;
$str .= 您的价格是 . $price;
echo $str;
?>
http://www.bkjia.com/phpjc/760151.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/760151.htmltecharticle通过组合模拟多重继承。 在php中不支持多重继承,如果我们向使用多个类的方法而实现代码重用有什么办法么? 那就是组合。在一个类中去...
