Home  >  Article  >  Backend Development  >  Explanation of PHP singleton mode (code example)

Explanation of PHP singleton mode (code example)

不言
不言forward
2018-10-24 17:30:032882browse

This article brings you an explanation (code example) about the PHP singleton mode. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The singleton pattern is a commonly used design pattern and can be seen in many frameworks. The singleton mode can ensure that there is only one instance of a class, thereby facilitating control of the number of instances and saving system resources.

<?php

use \Exception;

class Singleton
{
    /**
     * 对象实例
     * @var object
     /
    public static $instance;
    
    /**
     * 获取实例化对象
     /
    public static function getInstance()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        
        return self::$instance;
    }
    
    /**
     * 禁止对象直接在外部实例
     /
    private function __construct(){}
    
    /**
     * 防止克隆操作
     /
    final public function __clone()
    {
        throw new Exception(&#39;Clone is not allowed !&#39;);
    }
}

The singleton pattern may be used multiple times in a system. For easier creation, you can try to establish a general abstraction:

// SingletonFacotry.php
<?php

use \Exception;

abstract class SingletonFacotry
{
    /**
     * 对象实例数组
     * @var array
     /
    protected static $instance = [];
    
    /**
     * 获取实例化对象
     /
    public static function getInstance()
    {
        $callClass = static::getInstanceAccessor();
        if (!array_key_exists($callClass, self::$instance)) {
            self::$instance[$callClass] = new $callClass();
        }
        
        return self::$instance[$callClass];
    }
    
    abstract protected static function getInstanceAccessor();
    
    /**
     * 禁止对象直接在外部实例
     /
    protected function __construct(){}   
    
    /**
     * 防止克隆操作
     /
    final public function __clone()
    {
         throw new Exception(&#39;Clone is not allowed !&#39;);
    }
}
// A.php 
<?php

class A extends SingletonFactory
{
    public $num = 0;

    protected static function getInstanceAccessor()
    {
        return A::class;
    }
}

$obj1 = A::getInstance();
$obj1->num++;
var_dump($obj1->num); // 1
$obj2 = A::getInstance();
$obj2->num++;
var_dump($obj2->num); // 2

The above is the detailed content of Explanation of PHP singleton mode (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete