What are design patterns? A pattern is a solution to similar problems in a specific environment. It is the basis for reusable object-oriented software. There are actually many PHP design patterns. So, today I will tell you about PHP implementing a singleton pattern.
Concept:
Design patterns represent best practices and are usually adopted by experienced object-oriented software developers. Design patterns are solutions to common problems faced by software developers during the software development process. These solutions are the result of trial and error by numerous software developers over a long period of time.
php singleton mode definition
PHP singleton mode is a commonly used PHP software design pattern. It contains only one special class called a singleton in its core structure. The PHP singleton mode can ensure that the class to which this mode is applied in the system has only one instance. The PHP singleton mode instantiates itself and provides this instantiated class to the entire system.
php singleton mode code:
<?php class preferences { private $props = array(); private static $instance; private function __construct(){} public static function getInstance() { if(empty(self::$instance)) { self::$instance = new preferences(); } return self::$instance; } public function setProperty($key,$value) { $this->props[$key] = $value; } public function getProperty($key) { return $this->props[$key]; } } $ref = preferences::getInstance(); $ref->setProperty('name','ypp'); unset($ref);//移除引用 //var_dump(preferences::getInstance()); // echo $ref->getProperty('name'); $ref2 = preferences::getInstance();//值并未丢失 echo $ref2->getProperty('name'); //这里输出ypp
Summary
By defining a class, define a private constructor so that the outside world cannot Access the properties and methods of this class through instantiation, and then define a static method in the class. Instantiate the class by accessing this static method, so that you can globally access the properties and methods in this class and provide this to the entire system. kind.
Recommended related articles:
What is PHP singleton mode? How to implement singleton mode in php, php mode
PHP design pattern singleton pattern
php design pattern singleton pattern code,php design pattern
The above is the detailed content of PHP design pattern: A brief discussion of PHP singleton pattern (with code). For more information, please follow other related articles on the PHP Chinese website!