The singleton pattern is designed to prevent multiple instances of duplication, such as duplication of database connections, resulting in wasted resources.
The point is:
1/A class has only one object
2/class is self-created and cannot be declared by new
3/Purpose: This object is uniformly provided throughout the system.
Writing:
1/class defines a private static variable
Only private constructors are available in the 2/class
3/provides a static public function to create the private object itself.
4/Use __clone to prevent cloning
<?php//学习使用单例模式class Danli{ private static $db = null; private static $num = 0; private function __construct() { echo "对象已经构建完成:".self::$num."次\n"; } public static function getInstance() { if(self::$db instanceof self){ echo "已经实例化,不要重复实例\n"; return self::$db; }else{ self::$num +=1; return self::$db = new self(); } } static function test() { echo "调用成功\n"; } public function __clone() { echo "不能克隆哦"; }}$d = Danli::getInstance();$d->test();$c = Danli::getInstance();$c->test();$d= clone $c;//
PHP Pattern Design Single Example mode