php实现单例模式

WBOY
Release: 2016-06-23 13:24:33
Original
780 people have browsed it

<?PHPclass database{private  static $db;//设置一个静态成员变量静态方法static function getInstance(){    if(self::$db){            // 如果self::$db存在的话,不继续创建对象,直接将self::$db返回        return self::$db;    }else{            //如果self::$db 不能存在的话,直接创建对象并返回        self::$db = new database();        return self::$db;    }}}    $db = database::getInstance();?>
Copy after login

单例模式保证系统中一个类只有一个实例并且该实例可以从外界访问

节约了系统资源,如希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案


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 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!