Home > Backend Development > PHP Tutorial > PHP Design Pattern - Singleton_PHP Tutorial

PHP Design Pattern - Singleton_PHP Tutorial

WBOY
Release: 2016-07-13 17:52:49
Original
854 people have browsed it

Singleton pattern
The singleton design pattern is used to restrict a specific object to being created only once by providing access to a shared instance of itself.

Usage scenarios
For example, database instances generally use singleton mode.
Singleton pattern can reduce class instantiation
Code: Sourced from the InitPHP framework, first detect whether the class has been instantiated. If it is instantiated, use the object instance already stored in the static variable. If not, instantiate and save the object.
[php]
/**
* Framework core loading - all classes in the framework need to go out through this function
* 1. Singleton mode
* 2. Can load class files in -Controller, Service, View, Dao, Util, Library
* 3. Framework loading core function
* Usage: $this->load($class_name, $type)
* @param string $class_name class name
* @param string $type category
​*/ www.2cto.com
public function load($class_name, $type) {
$class_path = $this->get_class_path($class_name, $type);
$class_name = $this->get_class_name($class_name);
If (!file_exists($class_path)) InitPHP::initError('file '. $class_name . '.php is not exist!');
If (!isset(self::$instance['initphp'][$class_name])) {
        require_once($class_path);
If (!class_exists($class_name)) InitPHP::initError('class' . $class_name . ' is not exist!');
          $init_class = new $class_name;
           self::$instance['initphp'][$class_name] = $init_class;
}  
Return self::$instance['initphp'][$class_name];
}
Author: initphp

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478093.htmlTechArticleSingleton pattern By providing access to its own shared instance, the singleton design pattern is used to restrict specific objects to only be created. once. Usage scenarios, such as database instances, generally follow the singleton model...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template