duanchai0028 2011-06-03 00:13
浏览 31
已采纳

php mysql包装器类__destruct方法无法关闭数据库

Can anyone explain why mysql_close() fails when called from a class destructor? mysql_error() reports "Connection close failed."

<?php
class Database
{
    private $link_id = 0;
    private $query_id = 0;

    public $error = "";
    public $errorNumber = 0;
    public $affectedRows = 0;

    public function __construct($server, $user, $pass, $database)
    {
        $this->link_id = @mysql_connect($server, $user, $pass, false);

        if (!$this->link_id)
        {
            $this->DisplayError("Could not connect to server: <b>$this->server</b>.");
            die(mysql_error());
        }

        if(!@mysql_select_db($database, $this->link_id))
        {
            $this->DisplayError("Could not open database: <b>$this->database</b>.");
            die(mysql_error());
        }
    }

    public function __destruct()
    {
        if ($this->link_id)
        {
            if(!@mysql_close($this->link_id))
            {
                $this->DisplayError("Connection close failed.");
                die(mysql_error());
            }
        }
    }
  • 写回答

1条回答 默认 最新

  • duannuo4620 2011-06-03 00:23
    关注

    According to bug report #27903, it appears some resources are already cleaned up by the time class destructors are called due to end of script execution.

    In any case, as indicated in the manual...

    Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?