The article goes deep into PHP object-oriented, patterns and practices and points out that global variables are object-orientedProgramOne of the main causes of bugs encountered by members is that global variables bundle classes in a specific environment and disrupt encapsulation. However, in order to make all classes accessible to an object, we will not hesitate to tolerate the defects of global access.
To sum up, you do not need to use global variables and want to make every class accessible to objects. The key points of the problem are:
1. The object should be used by any object in the system.
2. objects should not be stored in global variables that will be rewritten.
3. The system should not contain more than one variable.
To solve this problem, you can use the singleton mode.
The implementation idea of the singleton mode is to set the class constructor to private permission, and indirectly instantiate the object using a static method and static attribute.
Class Singleton {Private Static $ instance = NULL; private $ props = array (); Private function _ construct () {} public static function getinstance () {If (empty (self:: $ instance) {self ::$ instance = new self ();} return self ::$ instance;} public function setprop ($ prop, $ value) {$ this-> props [$ prop] = $ value;} public function getprop ($ prop) {return $ this-> props [$ prop];} private function _ set ($ prop, $ value) {// omitted} private function _ Get () {// omitted} private function _ clone () {// omitted }}
The UML diagram of the singleton mode is as follows: