批改状态:合格
老师批语:子类的应用场景,其实还有, 但这三个显然是最主要的
子类的三个应用场景
1、代码复用
namespace _0930;
class demo1
{
// 属性(变量)
public $name;
public $age;
// 构造方法
public function __construct($name,$age)
{
$this -> name = $name;
$this -> age = $age;
}
// 方法(函数)
public function getInfor()
{
return '姓名:' . $this -> name . ',年龄:' . $this -> age ;
}
}
// 子类
// 1、代码复用
class sub1 extends demo1
{
//...
}
$sub1 = new sub1 ('蔡依林',39);
echo $sub1 -> getInfor();
echo '<hr>';点击 "运行实例" 按钮查看在线实例
2、功能拓展
// 子类
// 2、功能拓展
class sub2 extends demo1
{
public $salary;
public function __construct($name,$age,$salary)
{
parent::__construct($name,$age);
$this -> salary = $salary;
}
public function total(){
return $this -> salary *12;
}
}
$sub2 = new sub2('蔡依林',39,6000000);
echo $sub2 -> name . '的年收入:' . $sub2 -> total();
echo '<hr>';点击 "运行实例" 按钮查看在线实例
3、方法重写
// 子类
// 3、方法重写
class sub3 extends sub2
{
// 重写父类total()方法
public function total()
{
$total = parent::total();
switch ($total)
{
case $total > 100000000:
$total = ($total/10000) .'亿';
break;
case $total >10000;
$total =($total/10000) .'万';
break;
default :
$total = $total;
}
return $total;
}
}
$sub3 = new sub3 ('蔡依林',39,6000000);
echo $sub3 -> name . '的年收入:' . $sub3 ->total();
echo '<hr>';点击 "运行实例" 按钮查看在线实例
类成员访问限制符的使用场景
public: 默认, 类中,类外均可访问,子类中也可以访问。
protected:类中,类外不可访问, 但是子类中可以访问。
private:只允许在类中, 类外, 子类中不可访问。
<?php
namespace _930;
// public: 默认, 类中,类外均可访问,子类中也可以访问。
// protected:类中,类外不可访问, 但是子类中可以访问。
// private:只允许在类中, 类外, 子类中不可访问。
class Demo3
{
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->department === '***部' ? $this->position : '无权查看';
}
public function getSalary(){
// 工资: 如果不是财务部, 无权查看
return $this->department === '财务部' ? $this->salary : '无权查看';
}
}
// 类外部
$obj = new Demo3('小宋', '会计师', 88888, '财务部');
echo $obj->name, '<br>';
//echo $obj1->position; // position的属性声明为protected,外部不能访问
//echo $obj1->salary; // salary的属性声明为private: 外部不能访问
echo $obj->getPosition(), '<br>';
echo $obj->getSalary(), '<br>';
?>点击 "运行实例" 按钮查看在线实例
总结
子类继承父类时,会继承父类的属性和方法。其中 private 的属性需要通过在父类中定义的访问器来访问。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号