批改状态:合格
老师批语:子类的应用范围很广的, 凡是不适合,或者不方便,或者无法直接使用父类的场合下, 都可以或必须作子类来工作
子类的三个应用场景
namespace _0930;
class Demo11
{
//属性(变量)
public $priduct;
public $price;
//构造方法
public function __construct($product,$price)
{
$this->product=$product;
$this->price=$price;
}
//方法(函数)
public function getInfo()
{
return '商品名称:' . $this->product . ',商品价格:' . $this->price;
}
}点击 "运行实例" 按钮查看在线实例
代码复用
class sub1 extends Demo11
{
}
$sub1 = new sub1('iphone 11', 8800);
echo $sub1->getInfo() . '<hr>';点击 "运行实例" 按钮查看在线实例
2.功能扩展
class sub2 extends Demo11
{
//增加一个属性
public $num;
//构造方法
public function __construct($product,$price,$num)
{
parent::__construct($product,$price);
$this->num=$num;
}
//子类中增加一个新的方法:计算总和
public function total()
{
return round($this->price * $this->num,2);
}
}
$sub2 = new sub2('电脑',3980.2203,8);
echo $sub2->product . '的总价是:' . $sub2->total() . '<hr>';点击 "运行实例" 按钮查看在线实例
3.方法重写
class sub3 extends sub2
{
//重写total()
public function total()
{
$total = parent::total();
//设置折扣率
switch(true)
{
case($total > 20000&&$total < 40000):
$discountRate=0.88;
break;
case($total >= 40000&&$total < 60000):
$discountRate = 0.78;
break;
case($total >= 60000):
$discountRate = 0.68;
break;
default:
//小于或等于2000,不打折
$discountRate=1;
}
//打折后的价格
$discountprice=round($total*$discountRate,2);
if($discountRate<1){
$discountprice=$discountprice . '元,<span style="color:red">(' . $discountRate.'折)</span>';
}
//返回折扣价
return $discountprice;
}
}
$sub3 = new sub3('电脑',3800,13);
echo '折扣价是:' . $sub3->total();点击 "运行实例" 按钮查看在线实例
类成员的三种访问限制符的使用场景
public:类中、类外均可访问,子类中也可以访问
protected:类中可访问,类外 不可访问,但是子类可以访问
private:类中、类外都不可访问,子类也不可以访问
<?php
namespace _0930;
//访问控制符:public
//public:类中,类外均可访问,子类中也可以访问
//protected:类中可以访问,类外不可以访问,但是子类中可以访问
//private:只允许在类中,类外访问,子类中不可访问
class Demo4
{
//类中成员:属性,方法
//成员属性,成员方法
//对象属性:需要使用类的实例进行访问的成员属性
public $name; //姓名
protected $position; //职位
private $salary; //工资
protected $department; //部门
//构造方法
public function __construct($name,$position,$salary,$department)
{
$this->name=$name;
$this->position=$position;
$this->salary=$salary;
$this->department=$department;
}
//职位访问器/方法、函数
public function getPosition()
{
return $this->position;
}
//工资访问器/方法、函数
public function getSalary()
{
return $this->salary;
}
//部门访问器/方法、函数
public function getDepartment()
{
return $this->department;
}
}
$obj = new Demo4('诸葛亮','法师',6600,'中路');
echo $obj->name,'<br>';
// echo $obj->position,'<br>';
echo $obj->getPosition(),'<br>';
echo $obj->getSalary(),'<br>';
echo $obj->getDepartment(),'<br>';
class Sub extends Demo4
{
public function display()
{
// return $this->name;
// return $this->position;
return $this->salary;
}
}
echo '<hr>';
$sub = new Sub('高渐离','法师',8800,'中路');
echo $sub->display(),'<br>';
?>点击 "运行实例" 按钮查看在线实例
public:类中、类外均可访问,子类中也可以访问
protected:类中可访问,类外 不可访问,但是子类可以访问
private:类中、类外都不可访问,子类也不可以访问
子类的应用场景:(1)、代码复用(2)、功能扩展(3)、方法重写
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号