Home  >  Article  >  Backend Development  >  php PDO实例化一次

php PDO实例化一次

WBOY
WBOYOriginal
2016-06-20 12:38:551217browse

各位大神,下面是我写的一个连接类有些疑问,望解答

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();        }    }}


当我第一次执行方法调用DbOperator::getInstance()  这个时候$db为null, 满足条件new PDO,
但是当我执行第二次调用DbOperator::getInstance() 的时候$db 应该在第一次的时候就实例化了,但是我debug发现$db还是为null, 又执行了一次new PDO,这是怎么回事


回复讨论(解决方案)

$db 都改成 self::$db

private static $db = null; 
这个不要改

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn