PHP单例模式
如何确保只制造一个对象
1:对象的产生,需要new或者clone
2:防止产生过多的对象,要防止new和clone/继承
3:综上,没有对象时,允许new,并把对象缓存.下次直接返回该对象
核心思想
<?php final class sigle { /** * @var null */ protected static $ins =null; private function __construct() { } private function __clone() { } /** * CreateDTime: 2021/6/16 14:35 * Function: "" * @return sigle|null */ public static function getIns() { if (self::$ins==null){ self::$ins=new self(); } return self::$ins; } } $s1= sigle::getIns(); $s2= sigle::getIns(); if ($s1 === $s2){ echo '是一个对象'; }else{ echo '不是一个对象'; } /* new sigle(); class a extends sigle { }*/
实例
<?php class HttpService{ private static $instance; public function GetInstance(){ if(self::$instance == NULL){ self::$instance = new HttpService(); } return self::$instance; } public function Post(){ echo '发送Post请求', PHP_EOL; } public function Get(){ echo '发送Get请求', PHP_EOL; } } $httpA = new HttpService(); $httpA->Post(); $httpA->Get(); $httpB = new HttpService(); $httpB->Post(); $httpB->Get(); var_dump($httpA == $httpB);