singleton

<?php

class Mysql{
private static $_instance;
private $_db;
public function __clone(){
}
private function __construct($host,$usr,$pass,$port){
$this->_db = $this->db($host,$usr,$pass,$port);
}
public static function getInstance($host,$usr,$pass,$port){
if(!isset(self::$_instance) || !(self::$_instance instanceof self)){

//echo ‘init db instance’;
self::$_instance = new self($host,$usr,$pass,$port);
}
return self::$_instance;
}
private function db($host,$usr,$pass,$port=3306){
$mysqli = new mysqli($host,$usr,$pass,”,$port);
if ($mysqli->connect_error) {
die(‘Connect Error (‘ . $mysqli->connect_errno . ‘) ‘. $mysqli->connect_error);
}
return $mysqli;
}
public function query($sql){
$result = $this->_db->query($sql);
return $result;
}
public function fetch_assoc($sql){
$result = $this->query($sql);
$rows = array();
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
return $rows;
}
public function close(){
if(isset($this->_db) && !empty($this->_db)){
$this->_db->close();
}
}
}

/**
* test case
*/
/*
$host='localhost';
$user='root';
$pass='root';
$port=3306;
$instance = Mysql::getInstance($host,$user,$pass,$port);
$result = $instance->fetch_assoc('select * from test.lee limit 5');
$result = $instance->query("insert into test.lee values(null,'guest02',now());");
print_r($result);
*/
?>
此条目发表在 DesignPattern 分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*


*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>