Home>Article>Backend Development> How to implement singleton pattern in php
How to implement singleton mode in php: To implement singleton mode, you need to ensure that a class has only one instance and provide a global access point to access it. The singleton pattern does not create a copy of the instance, but returns a reference to the instance stored inside the singleton class.
Definition of singleton pattern:
(Recommended tutorial:php tutorial)
Ensure that a class has only one instance and provide a global access point to access it. It does not create a copy of the instance, but returns a reference to the instance stored inside the singleton class.
Three elements of the singleton pattern:
Requires a static member variable that holds the only instance of the class.
Constructors and clone functions must be declared private to prevent external programs from creating or making copies of the instance.
Must provide a public static method to access this instance, thereby returning a reference to the unique instance.
Code implementation:
class Singleton { //创建静态私有的变量保存该类对象 static private $instance; //防止使用new直接创建对象 private function __construct(){} //防止使用clone克隆对象 private function __clone(){} static public function getInstance() { //判断$instance是否是Singleton的对象,不是则创建 if (!self::$instance instanceof self) { self::$instance = new self(); } return self::$instance; } public function test() { echo "我是一个单例模式"; } } $sing = Singleton::getInstance(); $sing->test(); $sing2 = new Singleton(); //Fatal error: Uncaught Error: Call to private Singleton::__construct() from invalid context in $sing3 = clone $sing; //Fatal error: Uncaught Error: Call to private Singleton::__clone() from context
The above is the detailed content of How to implement singleton pattern in php. For more information, please follow other related articles on the PHP Chinese website!