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