批改状态:合格
老师批语:总结 的是对的
1、实例演示子类的三个应用场景
<?php
namespace _0930task1;
class commodity{
//属性
public $name;
public $model;
public $number;
// 构造方法
public function __construct($name,$model,$number){
$this->name=$name;
$this->model=$model;
$this->number=$number;
}
// 普通方法
public function getInfo(){
return '商品名称:'.$this->name.',型号:'.$this->model.',***数量:'.$this->number; }
}
// 子类作用一:代码复用
class child1 extends commodity{
//...
}
echo (new child1('华为','P30','10'))->getInfo();
echo '<hr>';
// 子类作用二:扩展父类中的功能(属性和方法)
class child2 extends commodity{
public $price;
public function __construct($name,$model,$number,$price){
parent::__construct($name,$model,$number);//继承父类中的原有方法
$this->price=$price;
}
// 增加一个新的方法
public function total(){
return round($this->number*$this->price,2);
}
}
echo '原价:'.(new child2('华为','P30','10','4567.123'))->total();
echo '<hr>';
// 子类作用三:方法重写
class child3 extends child2
{
public function total(){
$total=parent::total();
switch(true)
{
case($total>70000):
$discountRate=0.7;
break;
case($total>50000):
$discountRate=0.8;
break;
case ($total>20000):
$discountRate=0.9;
break;
default:
$discountRate=1;
}
return '折扣价为:'.$total*$discountRate.'折扣率:<span style="color:red">'.$discountRate.'<span>';
}
}
echo (new child3('华为','P30','10','4567.123'))->total();点击 "运行实例" 按钮查看在线实例
运行结果:

类的继承应用最多的功能应该是代码复用以及对功能扩展。
2、实例演示类成员的三种访问限制符的使用场景
<?php
namespace _0930task2;
class staff{
// 属性
public $name;
public $age;
private $gender;
private $salary;
protected $position;
protected $department;
// 构造方法
public function __construct($name,$age,$gender,$salary,$position,$department)
{
$this->name = $name ;
$this->age = $age;
$this->gender = $gender;
$this->salary = $salary;
$this->position =$position;
$this->department = $department;
}
public function getPublic(){
return 'public定义属性--姓名:'.$this->name.',年龄:'.$this->age;
}
// 获取私有控制符定义的属性
public function getPrivate(){
return 'private定义属性--性别:'.$this->gender.',薪资:'.$this->salary;
}
// 获取受保护控制符定义的属性
public function getProtected(){
return 'protected定义属性--职位:'.$this->position .',部门:'.$this->department;
}
}
$obj = new staff('Reid','19','男','20000','饮水机看守员','项目部');
echo $obj->getPublic(),'<hr>';
echo $obj->getPrivate(),'<hr>';
echo $obj->getProtected(),'<hr>';
class child1 extends staff{
public function getInfo1(){
return $this->department;
}
public function getInfo2(){
return $this->salary;
}
}
$obj = new child1('Reid','19','男','20000','饮水机看守员','项目部');
echo $obj->getInfo1(),'<hr>';
echo $obj->getInfo2();点击 "运行实例" 按钮查看在线实例
运行结果:


访问控制符定义属性:
public: 在类中和类外边都可以通过对象属性直接进行访问;
protected: 在类中和类外边都不能直接通过对象属性进行访问,通过在本类以及其子类中定义一个方法(访问器)来进行访问;
private:在类中和类外边都不能直接通过对象属性进行访问,通过在类中定义一个方法(访问器)来进行访问;不能直接在子类中定义方法来访问该属性,需要在调用父类中的方法进行访问。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号