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 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()???
求各位大神了
回复讨论(解决方案)
$db->prepare没有prepare方法,说明$db可能没有被实例化,在实例化之后打印db类里吗的$db变量看看
在构造函数中,self::$db 是 pdo 对象,所以有prepare 方法
在 getinstance 方法中,你又 self::$db = new self (); 把 self::$db 赋值为 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');
if (!self::$db instanceof self) { self::$db = new self (); } return self::$db;
多谢@xuzuning