简体   繁体   中英

Mysql error in closing the connection

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

Instead of using a home grown mysql wrapper, I would use PDO .

Failing that, PHP closes non-persistent DB connections on its own. It's possible that it does this before it calls object destructors obviating the need for that method.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM