doukun5339 2012-06-29 21:09
浏览 90
已采纳

关闭连接时出现Mysql错误

I have this class for DB interactions. It works fine.

<?php require_once('inc/config.inc.php'); ?>
<?php
final class MySQL {
private $link;

public function __construct($hostname, $username, $password, $database) {
    if (!$this->link = mysql_connect($hostname, $username, $password)) {
        //error('Error: Could not make a database link using ' . $username . '@' . $hostname);

    }
    if (!mysql_select_db($database, $this->link)) {
        //error('Error: Could not connect to database ' . $database);
    }
    //echo "open". time();
}

public function __destruct() {
    mysql_close(); // Problem In here
    //echo "closed". time();
}
}

$database=new MySQL(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
?>

But if I replace mysql_close(); with mysql_close($this->link);

I get an error: Warning: mysql_close() expects parameter 1 to be resource, null given

  • 写回答

2条回答 默认 最新

  • doupeng3501 2012-06-29 21:40
    关注

    The reason for this error is quite simple: $this->link is a resource. And (quoting the doc itself)...

    ... a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

    In other words, it's closed before your __destruct method is called. Even more, in mysql_close documentation it's said:

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

    By the way, I usually think of __destruct as of internal method (and quite rarely find use for it): PHP is not C++, the whole concept of freeing resources is rather different here (by a plenty of reasons). If I need to perform some cleanup task, I usually use register_shutdown_function, as it turned out to be way more predictable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退