您的位置:首页 > 编程语言 > PHP开发

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)、控制配置信息

如果系统中需要有一个类来全局控制某些配置信息, 那么使用单例模式可以很方便的实现.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: