php单列设计模式
2017-02-13 13:06
218 查看
class Singtest{ private static $_instance = null; private $link; private function __construct($host,$username,$password){ $this->link = new PDO("mysql:host=localhost;dbname=tpshop","root","123456"); } public function __clone(){//防止克隆 } public static function setMysql($host,$username,$password){//判断静态变量名是否为null,是的话就直接new对象并赋值给$_instance if (is_null(self::$_instance)) { self::$_instance = new Singtest($host,$username,$password); } return self::$_instance; } public function test(){ return $this->link; } } $host = "mysql:host=localhost;dbname=tpshop"; $username = 'root'; $password = 123456; $new = Singtest::setMysql($host,$username,$password);
单例模式在PHP中的应用场合:
(1)、应用程序与数据库交互
一个应用中会存在大量的数据库操作,比如过数据库句柄来连接数据库这一行为,使用单例模式可以避免大量的new操作,因为每一次new操作都会消耗内存资源和系统资源。
(2)、控制配置信息
如果系统中需要有一个类来全局控制某些配置信息, 那么使用单例模式可以很方便的实现.
相关文章推荐
- php基础设计模式大全(注册树模式、工厂模式、单列模式)
- php 设计模式之 单列模式
- php基础设计模式大全(注册树模式、工厂模式、单列模式)
- php基础设计模式 注册树模式、工厂模式、单列模式
- 一种PHP设计模式:DPT
- [转]五种常见的PHP设计模式
- 五种常见的PHP设计模式(择自互联网非本人所写)
- 五种常见的PHP设计模式
- [转]五种常见的PHP设计模式
- [PHP设计模式]Composite(组合)模式范例
- 一种PHP设计模式:DPT
- 架构师常用的五种 PHP 设计模式
- 介绍php设计模式中的工厂模式
- php设计模式介绍之值对象模式第1/5页
- 五种常见的 PHP 设计模式
- [介绍]PHP设计模式:DAO(数据访问对象模式)
- 五种常见的PHP设计模式
- [介绍]PHP设计模式:DAO(数据访问对象模式)
- php设计模式-中级
- php设计模式介绍之编程惯用法第1/3页