为什么mysql类比Database 类要先销毁 在User__destruct()中执行了sql 但是user类先销毁然后是mysql 而Database 没有调用销毁方法 按我的理解应该是 先销毁User 再销毁Database 再销毁mysql 断开连接应该在mysql 的__destruct()中,但实际要放在Database 的__destruct()中
链接: http://pan.baidu.com/s/1qWlwEUK 密码: 0lho 这是跟老师学习写的全部示例代码。
<?php
namespace Com;
class Database {
static private $db ;
private function __construct() //单例模式 只能new一次mysql
{
}
static function getInstance()
{
if(self::$db){
return self::$db;
}else{
// self::$db = new Database();
self::$db = new \Com\db\Mysql(); //$dbtest = new \Com\db\Mysqli(); 根据配置选择不同的数据库驱动
return self::$db;
}
}
function where(){
echo "调用了where \n";
return $this;
}
function order(){
echo "调用了order \n";
return $this;
}
function limit(){
echo "调用了limit \n";
return $this;
}
function __destruct()
{
echo "Database封装db被销毁";
$this->close(); //何时断开数据库连接
}
}
<?php
/**
* Created by PhpStorm.
* User: dxx
* Date: 2015/1/27
* Time: 14:34
*/
namespace com\db;
use Com\IDb;
class Mysql implements IDb{
private $conn ;
function __construct()
{
$this->connect('127.0.0.1','root','dxxDE0929','fly');
}
function connect($host,$user,$sec,$dbname)
{
$conn = mysql_connect($host,$user,$sec);
mysql_select_db($dbname,$conn);
$this->conn = $conn;
}
function query($sql)
{
$res = mysql_query($sql);
$resarr = '';
while ($line = mysql_fetch_array($res, MYSQL_ASSOC)) {
$resarr[] = $line;
}
mysql_free_result($res);
return $resarr;
}
function exec($sql)
{
$res = mysql_query($sql);
echo "\n执行exec\n";
return $res;
}
function close()
{
mysql_close($this->conn);
}
function __destruct()
{
//$this->close(); //此时断开数据库连接不行
echo "mysql被销毁";
}
}
<?php
namespace com\model;
use Com\Factory;
class User
{
public $uid ;
public $username ;
public $password ;
public $realname ;
private $tablename ;
private $record;
private $db;
function __construct($id)
{
$this->tablename = 'd_user';
$this->db = Factory::createDb();
$res = $this->db->query("select * from {$this->tablename} where uid={$id} limit 1");
// print_r($res);exit();
$this->record = $res[0] ;
$this->uid = $id;
$this->username = $res[0]['username'];
$this->password = $res[0]['password'];
$this->realname = $res[0]['realname'];
}
function __destruct()
{
$res = $this->db->exec("update {$this->tablename} set username='{$this->username}', realname='{$this->realname}'
where uid={$this->uid} limit 1");
echo "\n \n".$this->uid ."User被销毁";
}
}
在做迭代模式示例时发现:
为什么mysql类比Database 类要先销毁
在User__destruct()中执行了sql 但是user类先销毁然后是mysql 而Database 没有调用销毁方法
按我的理解应该是 先销毁User 再销毁Database 再销毁mysql 断开连接应该在mysql 的__destruct()中,但实际要放在Database 的__destruct()中