<span><?php </span><span>class </span>Db { <span>static private </span><span>$_instance</span>; <span>static private </span><span>$_connectSource</span>; <span>private </span>$_dbConfig <span>= array</span>( <span>'host' </span><span>=> </span><span>'127.0.0.1'</span>, <span>'user' </span><span>=> </span><span>'root'</span>, <span>'password' </span><span>=> </span><span>''</span>, <span>'database' </span><span>=> </span><span>'video'</span>, ); <span>private function </span><span>__construct</span>() { } <span>static public function </span><span>getInstance</span>() { <span>if</span>(<span>!</span>(<span>self::</span><span>$_instance </span><span>instanceof self</span>)) { <span>self::</span><span>$_instance </span><span>= new self</span>(); } <span>return self::</span><span>$_instance</span>; } <span>public function </span><span>connect</span>() { <span>if</span>(<span>!self::</span><span>$_connectSource</span>) { <span>self::</span><span>$_connectSource </span><span>= @</span><span>mysql_connect</span>($this<span>-></span>_dbConfig[<span>'host'</span>], $this<span>-></span>_dbConfig[<span>'user'</span>], $this<span>-></span>_dbConfig[<span>'password'</span>]); <span>if</span>(<span>!self::</span><span>$_connectSource</span>) { <span>throw new </span>Exception(<span>'mysql connect error ' </span><span>. </span><span>mysql_error</span>()); <span>//die('mysql connect error' . mysql_error()); </span>} <span>mysql_select_db</span>($this<span>-></span>_dbConfig[<span>'database'</span>], <span>self::</span><span>$_connectSource</span>); <span>mysql_query</span>(<span>"set names UTF8"</span>, <span>self::</span><span>$_connectSource</span>); } <span>return self::</span><span>$_connectSource</span>; } } <span>/*$connect = Db::getInstance()->connect(); </span><span>$sql = "select * from video"; </span><span>$result = mysql_query($sql, $connect); </span><span>echo mysql_num_rows($result); </span><p><span>var_dump($result);*/</span></p><p><span><img src="http://image.codes51.com/Article/image/20160622/20160622213950_9882.png" alt=" singleton单例模式"></span></p>
The above introduces the singleton singleton mode, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.