Rumah > pembangunan bahagian belakang > tutorial php > singleton单例模式

singleton单例模式

WBOY
Lepaskan: 2016-07-28 08:29:40
asal
1003 orang telah melayarinya
<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>
Salin selepas log masuk

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

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan