<?php
class Demo05{
// 对象属性
public $product;
public $price;
public function __construct($a,$b)
{
$this->product=$a;
$this->price=$b;
}
public function getInfo(){
return '品名:'.$this->product.',价格:'.$this->price.'<br>';
}
}
//创建子类继承自Demo05
//class Sub1 extends Demo05{
//
//}
////实例化子类
//$Sub1=new Sub1('手机','2500');
//echo $Sub1->getInfo();
//子类sub2,增加和方法."扩展父类功能"
class Sub2 extends Demo05{
// $num是子类中新添加的对象属性
public $num;
// 子类构造方法
public function __construct($a,$b,$c){
parent::__construct($a,$b);
$this->num=$c;
}
//计算总价
public function total(){
return $this->price*$this->num;
}
}
$sub2=new Sub2('电脑',4980,13);
echo $sub2->product.'的总价是:'.$sub2->total().'<hr>';
//方法重写(增加,减少功能)
//多重继承
class Sub3 extends Sub2
{
// 重写父类total()方法, 增加计算折扣价功能
public function total()
{
$total = parent::total();
// 设置折扣率
switch (true) {
case ($total >= 10000 && $total < 20000):
$discountRate = 0.98; // 98折
break;
case ($total > 20000 && $total < 40000):
$discountRate = 0.88; // 88折
break;
case ($total > 40000 && $total < 60000):
$discountRate = 0.78; // 78折
break;
case ($total >= 60000):
$discountRate = 0.68; // 68折
break;
default:
$discountRate = 1;
}
// 结果四舍五入,保留2位小数
return round($total*$discountRate, 2);
}
}
$sub3=new Sub3('电脑',4980,5);
echo '折扣价:'.$sub3->total();