Classical Example Analysis of Singleton Pattern Usage in php Design Pattern

  • 2021-12-21 04:31:29
  • OfStack

This article illustrates the singleton pattern usage of php design pattern. Share it for your reference, as follows:


<?php
/**
* @desc  Singleton pattern 
*  Purpose: To prevent excessive new Object and clone Object, when there is no object new Object and cache, always keeping the same 1 Object instances 
*  Features: php Is an in-process singleton, not like java Belonging to a singleton in memory 
* **/
class single{
protected static $ins = null;// Declaration 1 Static variables that store instances of a class 
private $name;// Declaration 1 Private instance variables 
/**
*  Privatization construction method , Prevent the constant creation of objects 
* **/
private function __construct(){
}
public static function getIns(){
if(self::$ins===null){
self::$ins = new self();
}
return self::$ins;
}
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}  
}
$single1 = single::getIns();
$single2 = single::getIns();
$single1->setName('hello world!');
$single2->setName('hello php!');
echo $single1->getName();// Output: hello php!
echo "<br/>":
echo $single2->getName();// Output: hello php!
/***
*  Analysis: The output results are all hello php!
*  The singleton schema object is adopted $single1 And $single2 Is equivalent, so the object $single1 And $single2 When setting the variables of the class, all point to 1 As a result, the variable value takes the latest set of the object 1 Values 
* **/

Run results:

hello php!
hello php!

More readers interested in PHP can check out the topics of this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: