Home > Article > Backend Development > php PDO实例化一次
各位大神,下面是我写的一个连接类有些疑问,望解答
class DbOperator{ private static $db = null; public static function getInstance() { try { if($db == null) { $db = new PDO("mysql:host=".localhost.";dbname=".test,root,root, array(PDO::ATTR_PERSISTENT => true)); $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER); } return $db; } catch (Exception $e) { die("数据库连接失败!".$e->getMessage()); } } function __destruct () { $db = null; } /** * 次函数主要是以集合的形式返回,或插入集合数据。 * @param unknown $strSql * @param unknown $array */ public static function executeArraySql($strSql, $array) { try { DbOperator::getInstance()->beginTransaction(); $stms = DbOperator::getInstance()->prepare($strSql); foreach ($array as $value) { $stms->execute($value); } DbOperator::getInstance()->commit(); }catch (PDOException $e) { print "Error: " . $e->getMessage() . "<br/>"; die(); } } /** * 次函数主要是用来指定条件查询 * @param unknown $strSql * @param unknown $array 查询参数 */ public static function executeSql($strSql,$array) { try { $stms = DbOperator::getInstance()->prepare($strSql); $bRet = $stms->execute($array); return $bRet; }catch (PDOException $e) { print "Error: " . $e->getMessage() . "<br/>"; die(); } }}
$db 都改成 self::$db
private static $db = null;
这个不要改