Correction status:qualified
Teacher's comments:代码中有一处漏写的分号 在测试的时候没报错么?
<?php class Demo { //对象属性 public $product; public $price; //构造函数 public function __construct($product,$price) { $this->product = $product; $this->price = $price; } //对象方法 public function getInfo() { return '品名:' . $this->product . ', 价格:' . $this->price . '<br>'; } } //创建一个子类继承自Demo class Sub1 extends Demo { } $sub1 = new Sub1('电话',1980); echo $sub1->getInfo() . '<br>'; //再创建一个子类继承自Demo,增加属性和方法,扩展父类功能 class Sub2 extends Demo { public $num; //数量 //子类构造方法 public function __construct($product, $price, $num) { parent::__construct($product, $price); $this->num = $num; } public function total() { return $this->price * $this->num; } } $sub2 = new Sub2('手机', 3980,15); echo $sub2->product . '的总价是:' . $sub2->total() . '<br>'; //方法重写 //为了促销,通常会根据总价,给一个折扣, //第三个子类,继承自Sub2,而Sub2又继承自Demo,这就形成了一个多层的继承关系 class Sub3 extends Sub2 { //重写父类total()方法,增加计算折扣价的功能 public function total() { //调用父类Sub2中的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; //不打折 } return round($total * $discountRate,2); } } $sub3 = new Sub3('手机',3980,15); echo '折后的价格是:' . $sub3->total() . '<br>'; //现在访问的是被 重写的total方法
点击 "运行实例" 按钮查看在线实例