You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP继承问题:Patient类扩展为Clinic类后输出NULL如何解决

故障原因
  • 缺少构造方法:Patient类未定义__construct构造函数,使用new Patient($name, $age, $gender)实例化时传入的三个参数没有被处理,无法赋值给类属性,导致所有属性默认值为NULL。
  • 继承语义不符合常规业务逻辑:Clinic(诊所)属于患者管理容器,和Patient(患者)不存在「是一个」的从属关系,该继承结构本身设计不合理。若老师要求必须使用继承实现,可按下方方案调整。
修复代码
<?php
class Patient{
    private $name;
    private $age;
    private $gender;

    // 新增构造方法,接收实例化传入的参数并赋值
    public function __construct($name, $age, $gender){
        $this->name = $name;
        $this->age = $age;
        $this->gender = $gender;
    }   

    public function getName(){
        return $this->name;
    }

    public function getAge(){
        return $this->age;
    }

    public function getGender(){
        return $this->gender;
    }
}

class Clinic extends Patient{
    private $patients = [];

    public function getPatients(){
        return $this->patients;
    }

    public function assignPatient($name, $age, $gender){
        $this->patients[] = new Patient($name, $age, $gender);
    }

    public function deletePatient($index){
        unset($this->patients[$index]);
        // 可选操作:重置数组索引,避免后续遍历出现索引断裂问题
        $this->patients = array_values($this->patients);
    }

    // 新增子类构造方法,处理父类构造的参数要求,无需额外传参
    public function __construct(){
        parent::__construct('', 0, '');
    }
}

$clinic = new Clinic();

$clinic->assignPatient("Patrick star",18,"Male");
$clinic->assignPatient("SpongeBob Squarepants",17,"Male");
$clinic->assignPatient("Eugene Krab",28,"Male");

$clinic->deletePatient(1);

var_dump($clinic->getPatients());
运行效果

修复后var_dump打印的患者对象中,name/age/gender属性都会正确显示赋值内容,不再返回NULL。删除索引为1的患者后,剩余两个患者信息会正常输出。

内容的提问来源于stack exchange,提问作者deeku ahlam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:54:02