当前位置:网站首页>Detailed explanation of PHP singleton mode

Detailed explanation of PHP singleton mode

2022-06-24 09:56:00 BigChen_ up

The singleton pattern :

It can prevent users from multiple instantiation operations , Instantiate only once ! Also called a single instance

  1. Users are not allowed to instantiate : Protective construction method new
  2. Provide a static method , A single instance can be generated
  3. Users are not allowed clone operation . Protect __clone The method can
  4. Static attribute , Used to save a single instance

The singleton pattern 3 private 1 Public principle :

 Private   structure 
 Private  clone
 Private   Static attribute 
 Open   Static methods 

Take the database class as an example :

  • Let's start with a wrong example :
class DB {
    
    // Construction method : new
    public function __construct() {
    
        echo ' Connect to database <br>';
    }

    public function __destruct() {
    
        echo ' Close the database <br>';
    }

    public function fetchAll() {
    
        echo ' Query operation !<br>';
    }
}

// Normal human practice 
$db = new DB();

$arr1 = $db->fetchAll();
$arr2 = $db->fetchAll();
$arr3 = $db->fetchAll();
$arr4 = $db->fetchAll();
$arr5 = $db->fetchAll();

echo '<hr>';

// Xiao Ming's practice :
// Xiao Ming thinks , new The object of   Only one query operation can be performed 

$db1 = new DB();
$db1->fetchAll();

$db2 = new DB();
$db2->fetchAll();

$db3 = new DB();
$db3->fetchAll();

$db4 = new DB();
$db4->fetchAll();

The following uses the singleton pattern to prevent the class from being instantiated multiple times :

class DB {
    
    // Static attribute :
    private static $instance = null;

    //Instance example 
    //$a = DB::getInstance()
    //$b = DB::getInstance()
    //$c = DB::getInstance()
    // Multiple calls ,  Only for the first time will I enter if Judge ,  Will instantiate .  When called again ,  because $instance It's worth it ,  So I won't go in again if,  It will not be instantiated again 
    public static function getInstance() {
    
        if (self::$instance == null) {
    
            self::$instance = new self;
        }
        return self::$instance;
    }

    // Construction method : new
    private function __construct() {
    
        echo ' Connect to database <br>';
    }

    // Private clone
    //
    private function __clone() {
    
        # code...
    }

    public function __destruct() {
    
        echo ' Close the database <br>';
    }

    public function fetchAll() {
    
        echo ' Query operation !<br>';
    }
}

$db1 = DB::getInstance();
$db1->fetchAll();
原网站

版权声明
本文为[BigChen_ up]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240807401630.html