PHP5,析构函数中的异常

 mobiledu2502905597 发布于 2023-02-06 17:05

我现在正在读"专业人士的PHP5",这是2006年的出版物.在一个例子中,他们在析构函数中抛出异常,很长一段时间我无法理解为什么我的析构函数中的最后一个异常不起作用,然后我搜索它并发现在PHP => 5.3中不可用于在析构函数中抛出异常.那么如何做得更好,如果在析构函数中我更新我的数据库if变量$needsUpdate = true;并关闭我的数据库连接,所以我想在数据库无法更新时抛出异常.例如异常我抛入我的数据库类,但在主文件中捕获它们,如下所示:

它的类Widget:

class Widget {

    private $_id;
    private $_name;
    private $_description; private $_hDB;
    private $_needsUpdating = false;

    public function __construct($widgetID) {

        $this->_hDB = new mysqli('localhost', 'phpbook', 'Un+)J=_hDB) {
            throw new Exception('?? ??????? ??????????? ? ???? ??????');
        }
        $sql = "SELECT `name`, `description` FROM widgets WHERE id = '$widgetID'";
        $rs = $this->_hDB->query($sql);

        if (! $rs) {
            throw new Exception("????????? ?????? ??? ?????? ???? ??????");
        }

        if (! $rs->num_rows) {
            throw new Exception("???????? ?????? ? ???? ?????? ???????????");
        }
        $data = $rs->fetch_assoc();
        $this->_id = $widgetID;
        $this->_name = $data['name'];
        $this->_description = $data['description'];

    }

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

    public function getDescription() {
        return $this->_description;
    }

    public function setName($name) {
        $this->_name = $name;
        $this->_needsUpdating = true;
    }

    public function setDescription($description) {
        $this->_description = $description;
        $this->_needsUpdating = true;
    }

    public function __destruct() {
        if (! $this->_needsUpdating) {
            return;
        }

        $sql = 'UPDAT2E `widgets` SET';
        $sql .= ' `name` = "' . $this->_hDB->real_escape_string($this->_name) . '",';
        $sql .= ' `description` = "' . $this->_hDB->real_escape_string($this->_description) . '" ';
        $sql .= 'WHERE id = ' . $this->_id;


        $rs = $this->_hDB->query($sql);
        if (! $rs) {
            throw new Exception("????????? ?????? ??? ?????????? ???? ??????");
        }
        $this->_hDB->close();
    }
}

这是主要文件.

try {
    $widget = new Widget(2);
    echo "Name: " . $widget->getName() . "
\n"; echo "Description: " . $widget->getDescription() . "
\n"; $widget->setName("Iphone 4 / 64GB"); $widget->setDescription("New Phone, black color, blablabla"); } catch (Exception $e) { die("An error has occurred: " . $e->getMessage()); }

最后一个例外__destruct()没有奏效.

如果更新数据库失败,有没有一种很好的方法来抛出异常?还是有其他正确的方法,我不明白的东西?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有