慢慢长寻夜,明月高空挂php
__construct() - 在每次建立新对象时先调用此方法mysql
__destruct() - 对象的全部引用都被删除或者当对象被显式销毁时执行sql
<?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)