Home > php教程 > php手册 > body text

php单例模式示例分享,php模式示例分享

WBOY
Release: 2016-06-13 09:14:50
Original
1123 people have browsed it

php单例模式示例分享,php模式示例分享

单例模式主要使用于数据库的连接, 确保数据库一个类只有一个实例, 并且向整个系统提供这个实例。从而避免new操作消耗资源, 同时避免数据库出现too many connection信息.

要点有三个: 1. 必须只有一个实例。 2. 必须自动创建这个实例。 3. 必须向整个系统提供这个实例。

复制代码 代码如下:


     class mysql{
        privete static $instance ;//保存实例
         //构造函数声明为private, 防止直接创建对象
        privete function __construct(){
             // 实例化
         }
         //单例方法, 判断是否已经实例化,只实例化一次
         public static function getInstance (){
             if(!isset( self::$instance )){
                self ::$instance = new self();
             }
             return self:: $instance;
         }
         //防止克隆对象
         private function __clone (){
             trigger_error ("not allow to clone.");
         }
         function test(){
             echo "test" ;
         }
     }
     $conn = mysql::getInstance ();
     $conn->test ();
?>

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!