class connector {
private static $db;
function __construct() {
$this->db = null;
$this->connect();
}
private function connect() {
$this->db = new PDO('mysql:host=localhost;dbname=database;charset=utf8','user','pass');
}
public static function getDB() {
if (!isset(self::$db)) {
self::$db = new connector();
}
return self::$db;
}
EDITED
// this was my original function, I had reduced it for less space. my deepest regrets, I won't do it again.
public function getValue($sql,$val='') {
if ($val != '') {
$data = $this->db->prepare($sql);
$data->execute($val);
return $data->fetch(PDO::FETCH_COLUMN);
}
else {
return $this->db->query($sql)->fetch(PDO::FETCH_COLUMN);
}
使用这个类,我可以很容易地使用PDO的数据库对象从任何地方,使用自定义功能。
$db = connector::getDB();
// var_dump()
db:object(connector)#1 (1) {
["db":"connector":private]=>
object(PDO)#2 (0) {
}
}
$db->getValue('SELECT foo FROM bar'); //succeeds
$db->query('SELECT foo FROM bar'));
// throws
// Fatal error: Call to undefined method connector::query()
如果我回到实际的对象PARAM而不是整个的对象:
return self::$db->db;
db:object(PDO)#2 (0) {
}
查询互换角色
$db->getValue('SELECT foo FROM bar');
// throws
// Fatal error: Call to undefined method connector::getValue()
$db->query('SELECT foo FROM bar')); //succeeds
怎样才可以有两个与同一个对象 ,有效利用$db->query()
和$db->getValue()
在同一个脚本。