Home >Backend Development >PHP Problem >Can php implement singleton?
php can implement a singleton. The method of implementing a singleton is: 1. Apply for a private static member variable to save the only instance of the class; 2. Declare a private constructor to prevent objects from being created outside the class. ;3. Declare a static public method for external acquisition of the only instance.
The operating environment of this article: Windows7 system, PHP7.1 version, DELL G3 computer
How to implement a singleton in PHP
Apply for a private static member variable to save the only instance of the class
Declare a private constructor to prevent objects from being created outside the class
Declare a static public method for external acquisition of a unique instance
After completing these three steps, it is a singleton, but this singleton The example is not safe. If you want this singleton to be safe, you need the following two steps (please add if there are any imperfections)
Declare a private cloning method to prevent the object from being cloned
Override the __sleep method and leave the return blank to prevent serialization and deserialization from obtaining new objects
<?php /** * 单列模式(防止对象克隆、对象序列化反序列化) * Created by PhpStorm. * User: Jeaforea * Date: 2019/3/14 * Time: 17:56 */ namespace Kanshenmekan\Buzhunkan\Zaikandasini; class SetSingleton{ private static $new; //申请一个私有的静态成员变量来保存该类的唯一实例 private function __construct() {} //声明私有的构造方法,防止类外部创建对象 public static function instance () { //声明一个静态公共方法,供外部获取唯一实例 if (!(self::$new instanceof self)) { self::$new = new self; } return self::$new; } private function __clone() {} //声明私有的克隆方法,防止对象被克隆 public function __sleep() { //重写__sleep方法,将返回置空,防止序列化反序列化获得新的对象 return []; } }
[Recommended learning:PHP video tutorial】
The above is the detailed content of Can php implement singleton?. For more information, please follow other related articles on the PHP Chinese website!