慢慢長尋夜,明月高空掛
__construct() - 在每次創建新對象時先調用此方法
__destruct() - 對象的所有引用都被刪除或者當對象被顯式銷毀時執行
<?php
/**
* 清晰的認識__construct() __destruct
*/
class Example {
public static $link;
//在類實例化的時候自動加載__construct這個方法
public function __construct($localhost, $username, $password, $db) {
self::$link = mysql_connect($localhost, $username, $password);
if (mysql_errno()) {
die('錯誤:' . mysql_error());
}
mysql_set_charset('utf8');
mysql_select_db($db);
}
/**
* 通過__construct鏈接好數據庫然后執行sql語句......
*/
//當類需要被刪除或者銷毀這個類的時候自動加載__destruct這個方法
public function __destruct() {
echo '<pre>';
var_dump(self::$link);
mysql_close(self::$link);
var_dump(self::$link);
}
}
$mysql = new Example('localhost', 'root', 'root', 'test');
結果:
resource(2) of type (mysql link) resource(2) of type (Unknown)
