批改状态:未批改
老师批语:
构造方法:
构造方法用来初始化对象成员
构造方法: public function __construct(){...}
class Demo04
{
// 对象属性
public $product;
public $price;
// 构造方法
public function __construct($product, $price)
{
$this->product = $product;
$this->price = $price;
}
// 对象方法
public function getInfo()
{
return '品名: ' .$this->product .', 价格: ' . $this->price . '<br>';
}
}类的继承 :
关键字:extends
功能作用:能够在父类的基础上扩展(重写)父类的功能和属性
<?php
// 关键词: 类的继承,功能扩展, 方法重写
// 将Demo04类代码复制过来,改为Demo05
class Demo05
{
// 对象属性
public $product;
public $price;
// 构造方法
public function __construct($product, $price)
{
$this->product = $product;
$this->price = $price;
}
// 对象方法
public function getInfo()
{
return '品名: ' .$this->product .', 价格: ' . $this->price . '<br>';
}
}
// 子类Sub1, 代码复用
class Sub1 extends Demo05
{
// ...
}
// 实例化子类Sub, 尽管子类中无任何成员,但是它可以直接调用父类Demo05中的全部成员
$sub1 = new Sub1('手机', 3500);
echo '总价: ' . $sub1->getInfo() . '<hr>';
/*****************************************************************/
// 子类Sub2, 增加属性和方法,扩展父类功能
class Sub2 extends Demo05
{
public $num; // 数量
// 子类的构造方法
public function __construct($product, $price, $num)
{
// 调用父类的构造方法,否则还要手工把父类中的属性初始化语句全部写一遍
// parent:: 调用被覆写的父类方法内容
parent::__construct($product, $price);
// 只需要添加子类中的成员初始化代码
$this->num = $num;
}
// 计算总价
public function total()
{
return $this->price * $this->num;
}
}
// 实例化子类
$sub2 = new Sub2('电脑',4980, 13);
echo $sub2->product . '的总价: ' . $sub2->total() . '<hr>';
/***************************************************************/
// 方法重写
// 为了促销, 通常会根据总价,给予一定的折扣,刺激消费者***更多的商品或服务
// 第三个子类, 继承自Sub2, 而Sub2又继承自Demo05,这就形成了多层给的继承关系
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);
}
}
// 实例化子类, 88折
$sub3 = new Sub3('电脑',4980, 13);
echo '折扣价: ' . $sub3->total();
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号