问题描述
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;
}
已编辑
// 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数据库对象.
using this class I can easily use the pdo database object from anywhere, with custom functions.
$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()
如果我返回实际的对象参数而不是整个对象:
if I return the actual object param instead of the whole object:
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()
来使两个对象同一个对象.
How can I have both with the same object, effectively using $db->query()
and $db->getValue()
in the same script.
推荐答案
首先,您的getValue()
方法缺乏一项基本功能-对准备好的语句的支持.没有运行动态查询的能力,它的价值几乎为零.
First of all, your getValue()
method lacks one essential feature - support for prepared statements. Without ability to run dynamical queries it's value is close to nothing.
第二,无论如何,如果您正在使用单例-则不需要额外的方法来获取实例-如今,单例可以自己完成.
Second, if you are using a singleton anyway - then there is no need for the extra method to get an instance - nowadays singleton can do it just by itself.
那是什么呢?我编写它的目的是利用整洁的方法链来减少PDO的使用难度. DB
静态类已经是 一个PDO实例,无需通过额外的调用实例化它.因此,您可以在任何地方运行任何PDO命令:
What about this one? I wrote it to make PDO usage less wordy, utilizing neat method chaining. DB
static class is already a PDO instance, without the need to instantiate it with extra call. As a result, you can run any PDO command just anywhere:
DB::query('SELECT foo FROM bar LIMIT 1')->fetchColumn();
占用的空间比您少,但至少可以让您访问完整的PDO语法,包括对准备好的语句的支持
It takes little more space than yours but at least it is giving you access to full PDO syntax, including support for prepared statements
DB::prepare('SELECT foo FROM bar WHERE id=?')->execite([$id])->fetchColumn();
以及所有其他提取方法
DB::query('SELECT foo FROM bar')->fetchAll(PDO::FETCH_COLUMN);
这篇关于在同一数据库对象上使用pdo query()和自定义getValue()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!