Home > Backend Development > PHP Tutorial > PHP中怎么实现Singleton(单例模式)

PHP中怎么实现Singleton(单例模式)

WBOY
Release: 2016-06-13 13:11:58
Original
1003 people have browsed it

PHP中如何实现Singleton(单例模式)

单例模式有以下的特点:

?

  1. 单例类只能有一个实例。
  2. 单例类必须自己创建自己的唯一的实例。
  3. 单例类必须给所有其他对象提供这一实例。

代码:

Singleton.php:

class Singleton
{
??? private static $instance;

??? private function __construct()
??? {
??? }

??? public static function getInstance()
??? {
??????? if(self::$instance == null)
??????? {
??????????? self::$instance = new Singleton();
??????? }

??????? return self::$instance;
??? }
}
?>

?

在使用的时候,因为构造方法是private(私有)的,所以是不能直接实例化的,必须使用类似下面的方法:

例子:

require_once('Singleton.php');

$instance = Singleton::getInstance();
?>

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