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

PHP如何在类中实现删除对象功能?deletePatient方法调用问题求助

问题核心错误点
  • 类职责混淆:你将Clinic(诊所,负责管理患者)和Patient(患者,存储单个患者属性)两个逻辑揉在同一个类里,导致你存到$patients数组里的全是同一个对象的引用,三个元素最终会被覆盖为最后一次赋值的患者信息,不存在三个独立的患者对象。
  • 患者ID逻辑完全失效:Patient方法内的$id是局部变量,反复赋值后仅保留最后一次的$gender值,既没有存为对象属性,也没有全局唯一的生成逻辑,后续根本无法通过ID定位患者。
  • 删除逻辑完全错误:deletePatient方法内调用需要3个参数的Patient方法仅传1个参数会直接报参数缺失错误;(unset) $id是类型转换语法,只会返回null,根本不会删除任何对象,你在这里的var_dump打印的也只是无意义的null值。
  • 作用域逻辑错误:你想删除的患者存在于全局的$patients数组里,类内的方法默认访问不到这个全局数组,自然不可能完成删除操作。
正确实现方案

拆分两个类的职责,让Clinic类统一管理所有患者的增删操作,每个Patient是独立的实例有唯一ID,实现代码如下:

<?php
// 独立患者类,存储单个患者的属性
class Patient {
    public $id;
    public $name;
    public $age;
    public $gender;

    public function __construct($id, $name, $age, $gender) {
        $this->id = $id;
        $this->name = $name;
        $this->age = $age;
        $this->gender = $gender;
    }
}

// 诊所类,负责管理所有患者
class Clinic {
    // 内部维护患者列表和自增ID
    private $patients = [];
    private $nextId = 1;

    // 新增患者
    public function assignPatient($name, $age, $gender) {
        $patient = new Patient($this->nextId, $name, $age, $gender);
        $this->patients[$this->nextId] = $patient;
        $this->nextId++;
        return $patient;
    }

    // 删除指定ID的患者
    public function deletePatient($id) {
        if (isset($this->patients[$id])) {
            unset($this->patients[$id]);
            // 这里可以打印删除结果验证
            var_dump("ID为{$id}的患者已删除");
            return true;
        }
        var_dump("未找到ID为{$id}的患者");
        return false;
    }

    // 获取所有患者列表
    public function getPatients() {
        return $this->patients;
    }
}

// 调用示例
$clinic = new Clinic();
$clinic->assignPatient("Patrick star",18,"Male");
$clinic->assignPatient("SpongeBob Squarepants",17,"Male");
$clinic->assignPatient("Eugene Krab",28,"Male");

// 删除ID为2的患者
$clinic->deletePatient(2);

// 遍历输出所有患者
foreach($clinic->getPatients() as $patient) {
    echo $patient->name . " ";
    echo $patient->age . " ";
    echo $patient->gender . "\n"; 
}

运行上述代码会输出ID1和ID3的患者信息,ID2的患者已被成功删除。

内容的提问来源于stack exchange,提问作者Aldrin James Santos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:27:03