How to implement a single-column mode in php: 1. Create a private variable to save the object; 2. Prohibit the use of new; 3. Prohibit cloning; 4. Determine whether the object exists; 5. Implement the single-column mode.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
How does php implement a single column mode?
PHP implements a single column mode
Code:
<?php final class Singleton { //1.创建私有变量保存该对象 private static $instance; //2.禁止使用new private function __construct(){ } //3.禁止克隆 private function __clone() { } //4.判断对象是否存在 public static function getInstance() { if (!self::$instanceinstanceof self) { self::$instance= new self(); } return self::$instance; } public function test(){ echo '测试单列模式'; } } $singleton = Singleton::getInstance(); $singleton->test(); //实现单列模式的意义,减少资源的占用
Recommended study: "PHP Video Tutorial"
The above is the detailed content of How to implement a single column mode in php. For more information, please follow other related articles on the PHP Chinese website!