Home  >  Article  >  Backend Development  >  Example description of php singleton mode

Example description of php singleton mode

无忌哥哥
无忌哥哥Original
2018-06-28 16:09:071251browse

* Singleton mode: Only one instance of a class is allowed to be created

* For example:

* 1. A site can only connect to one database connection object

* 2. A site is only allowed to have one instance object of the configuration class

class Config1 {}
class Config
{
* 必须先声明一个静态私有属性:用来保存当前类的实例
* 1. 为什么必须是静态的?因为静态成员属于类,并被类所有实例所共享
* 2. 为什么必须是私有的?不允许外部直接访问,仅允许通过类方法控制方法
* 3. 为什么要有初始值null,因为类内部访问接口需要检测实例的状态,判断是否需要实例化
private static $instance = null;
//保存用户的自定义配置参数
private $setting = [];
//构造器私有化:禁止从类外部实例化
private function __construct(){}
//克隆方法私有化:禁止从外部克隆对象
private function __clone(){}
        //因为用静态属性返回类实例,而只能在静态方法使用静态属性
        //所以必须创建一个静态方法来生成当前类的唯一实例
public static function getInstance()
{
            //检测当前类属性$instance是否已经保存了当前类的实例
            if (self::$instance == null) {
                //如果没有,则创建当前类的实例
                self::$instance = new self();
            }
            
            //如果已经有了当前类实例,就直接返回,不要重复创建类实例
            return self::$instance;
}
//设置配置项
public function set($index, $value)
{
$this->setting[$index] = $value;
}
//读取配置项
public function get($index)
{
return $this->setting[$index];
}
}
$obj1 = new Config1;
$obj2 = new Config1;
var_dump($obj1,$obj2);
echo &#39;<hr>&#39;;
//实例化Config类
$obj1 = Config::getInstance();
$obj2 = Config::getInstance();
var_dump($obj1,$obj2);
$obj1->set(&#39;host&#39;,&#39;localhost&#39;);
echo $obj1->get(&#39;host&#39;);

The above is the detailed content of Example description of php singleton mode. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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