分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

php 单例模式

发布时间:2023-09-06 01:53责任编辑:顾先生关键词:暂无标签

单例模式
当需要保证某个对象只能有一个实例的时候,单例模式非常有用。它把创建对象的控制权委托到一个单一的点上,任何时候应用程序都只会仅有一个实例存在。

单例模式中必须包含:private 的构造函数、静态变量、公共静态方法、private clone方法。

下面举个栗子

<?php/** mysql 单例*/class mysql{ ???private $host ???=‘yourhost‘; //数据库主机 ???private $user ????= ‘youruser‘; //数据库用户名 ???private $pwd ????= ‘yourpwd‘; //数据库用户名密码 ???private $database = ‘database‘; //数据库名 ???private $charset = ‘utf8‘; //数据库编码,GBK,UTF8,gb2312 ???private $link; ????????????//数据库连接标识; ???private $rows; ????????????//查询获取的多行数组 ???static $_instance; //存储对象 ???/** ????* 私有构造函数 ????*/ ???private function __construct($pconnect = false) { ???????if (!$pconnect) { ???????????$this->link = @ mysql_connect($this->host, $this->user, $this->pwd) or $this->err(); ???????} else { ???????????$this->link = @ mysql_pconnect($this->host, $this->user, $this->pwd) or $this->err(); ???????} ???????mysql_select_db($this->database) or $this->err(); ???????$this->query("SET NAMES ‘{$this->charset}‘", $this->link); ???????return $this->link; ???} ???/** ????* 防止被克隆 ????* ????*/ ???private function __clone(){} ???public static function getInstance($pconnect = false){ ???????if(FALSE == (self::$_instance instanceof self)){ ???????????self::$_instance = new self($pconnect); ???????} ???????return self::$_instance; ???} ???/** ????* 查询 ????*/ ???public function query($sql, $link = ‘‘) { ???????$this->result = mysql_query($sql, $this->link) or $this->err($sql); ???????return $this->result; ???} ???/** ????* 单行记录 ????*/ ???public function getRow($sql, $type = MYSQL_ASSOC) { ???????$result = $this->query($sql); ???????return @ mysql_fetch_array($result, $type); ???} ???/** ????* 多行记录 ????*/ ???public function getRows($sql, $type = MYSQL_ASSOC) { ???????$result = $this->query($sql); ???????while ($row = @ mysql_fetch_array($result, $type)) { ???????????$this->rows[] = $row; ???????} ???????return $this->rows; ???} ???/** ????* 错误信息输出 ????*/ ???protected function err($sql = null) { ???????????}}//用例$db = mysql::getInstance();$db2 = mysql::getInstance();$data = $db->getRows(‘select * from blog‘);//print_r($data);//判断两个对象是否相等if($db === $db2){ ???echo ‘true‘;}?>

php 单例模式

原文地址:https://www.cnblogs.com/pfdltutu/p/9019194.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved