本篇文章给大家带来的内容是关于php单例模式的讲解(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
单例模式是一种比较常用的设计模式,在很多框架中可以看到它的身影。通过单例模式可以确保类只有一个实例化,从而方便对实例个数的控制并节约系统资源。
<?phpuse \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('clone is not allowed !'); }}
一个系统中可能会多次使用到单例模式,为了更加方便的创建,可以试着建立一个通用的抽象:
// singletonfacotry.php<?phpuse \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('clone is not allowed !'); }}
// a.php <?phpclass 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
以上就是php单例模式的讲解(代码示例)的详细内容。