首页 >后端开发 >php教程 >singleton单例模式

singleton单例模式

WBOY
WBOY原创
2016-07-28 08:29:401003浏览
<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></span>

以上就介绍了 singleton单例模式,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn