在构造方法中使用静态属性保存的pdo资源句柄在其他方法中无法调用??? ?php classdb{ protected$link='127.0.0.1'; protected$dbname='think'; staticpublic$db; privatefunction__construct(){ try{ self::$db=newpdo(mysql:host={$this-link};dbname={$t
在构造方法中使用静态属性保存的pdo资源句柄在其他方法中无法调用???
link};dbname={$this->dbname},'root','root');
}catch (pdoexception $e){
die(连接出错:.$e->getmessage());
}
$sql = ' select * from user where id=? and username=? and email=? ';
$stmt = self::$db->prepare($sql);
$stmt->execute([0=>'13',1=>'12',2=>'12']);
echo '';
print_r($stmt->fetchall(pdo::fetch_assoc));
echo $stmt->rowcount();
}
//静态方法,单例统一访问入口
static public function getinstance() {
if (is_null ( self::$db ) || isset ( self::$db )) {
self::$db = new self ();
}
return self::$db;
}
public function test(){
$sql = ' select * from user where id=? and【本文来自鸿网互联 (http://www.68idc.cn)】 username=? and email=? ';
$stmt = self::$db->prepare($sql);
$stmt->execute([0=>'13',1=>'12',2=>'12']);
echo '';
print_r($stmt->fetchall(pdo::fetch_assoc));
echo $stmt->rowcount();
}
}
$db = db::getinstance();
$db->test();
我把test方法复制在构造方法没有问题,为什么在test方法中会出现call to undefined method db::prepare()???
求各位大神了
------解决思路----------------------
你至少应写作class db{
protected $link = '127.0.0.1';
protected $dbname = 'think';
static public $db;
static public $_db;
private function __construct(){
try{
self::$_db = new pdo(mysql:host={$this->link};dbname={$this->dbname},'root','root');
}catch (pdoexception $e){
die(连接出错:.$e->getmessage());
}
}
//静态方法,单例统一访问入口
static public function getinstance() {
if (is_null ( self::$db )
------解决思路----------------------
isset ( self::$db )) {
self::$db = new self ();
}
return self::$db;
}
public function test(){
$sql = ' select * from user where id=? and username=? and email=? ';
$stmt = self::$_db->prepare($sql);
$stmt->execute([0=>'13',1=>'12',2=>'12']);
echo '';
print_r($stmt->fetchall(pdo::fetch_assoc));
echo $stmt->rowcount();
}
}
$db = db::getinstance();
$db->test();
pdo 本身已经封装的很好了,如确需要进一步封装以简化调用代码
那么应该从 pdo 继承一个 db 类,如class db extends pdo {
private static $_instance;
function __construct() {
$options = array(
pdo::mysql_attr_init_command => set names gbk,
pdo::attr_errmode => pdo::errmode_exception,
pdo::attr_default_fetch_mode => pdo::fetch_assoc,
);
parent::__construct('mysql:dbname=test', 'root', '', $options);
}
//执行各种 sql 指令,并可通过参数 $param 进行扩展
function query($sql, $param=null) {
$res = [];
try {
$rs = parent::query($sql);
do {
if($t = $rs->fetchall()) $res[] = $t;
}while($rs->nextrowset());
return $res;
} catch (pdoexception $e) {
die( error!: . $e->getmessage() . \n );
// die();
}
}
//查询并返回单条记录
static function fetch($sql) {
if(! self::$_instance) self::$_instance = new self;
return self::$_instance->query($sql)[0][0];//->fetch();
}
//查询并以数组方式返回多条记录
static function fetchall($sql) {
if(! self::$_instance) self::$_instance = new self;
$res = self::$_instance->query($sql);//->fetchall();
if(count($res) == 1) return current($res);
}
}
这样你就有机会这样使用了
$r = db::fetch(select * from user where name='my');
