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

PHP设计模式之单例模式

WBOY
Release: 2016-06-13 09:15:54
Original
886 people have browsed it

PHP设计模式之单例模式

  单例模式 :使得类的一个对象成为系统中的唯一实例.

  PHP中使用单例模式最常见的就是数据库操作了。避免在系统中有多个连接数据库的操作,浪费系统资源的现象,就可以使用单例模式。每次对数据库操作都使用一个实例。

  简单示例

  class AClass {

  // 用来存储自己实例

  public static $instance;

  // 私有化构造函数,防止外界实例化对象

  private function __construct() {}

  // 私有化克隆函数,防止外界克隆对象

  private function __clone() {}

  // 静态方法,单例访问统一入口

  public static function getInstance() {

  if (!(self::$instance instanceof self)){

  self::$instance = new self();

  }

  return self::$instance;

  }

  // test

  public function test() {

  return "done";

  }

  // 私有化克隆函数,防止外界克隆对象

  private function __clone() {}

  }

  class BClass extends AClass{

  }

  // 获取实例

  $aclass = AClass::getInstance();

  $bclass = BClass::getInstance();

  // 调用方法

  echo $aclass->test();

  对一些比较大型的应用来说,可能连接多个数据库,那么不同的数据库公用一个对象可能会产生问题,比如连接句柄的分配等,我们可以通过给$instance变成数组,通过不同的参数来控制

  简单示例

  class DB {

  // 用来存储自己实例

  public static $instance = array();

  public $conn;

  // 私有化构造函数,防止外界实例化对象

  private function __construct($host, $username, $password, $dbname, $port) {

  $this->conn = new mysqli($host, $username, $password, $dbname, $port);

  }

  // 静态方法,单例访问统一入口

  public static function getInstance($host, $username, $password, $dbname, $port) {

  $key = $host.":".$port;

  if (!(self::$instance[$key] instanceof self)){

  self::$instance[$key] = new self($host, $username, $password, $dbname, $port);#实例化

  }

  return self::$instance[$key];

  }

  //query

  public function query($ql) {

  return $this->conn->query($sql);

  }

  // 私有化克隆函数,防止外界克隆对象

  private function __clone() {}

  //释放资源

  public function __destruct(){

  $this->conn->close();

  }

 

  }

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!