PHP 单例模式

/***********************************************/
/******************单列模式*********************/
/***********************************************/


1.1 单列模式

单例模式: 一个类只能有一个实例

构造函数 非public

三大原则:

1: 构造函数 需要标记为非public(只能被其自身实例化)

2: 拥有一个保存类的实例的静态成员变量 $_instance

3: 拥有一个访问这个实例的公共的静态方法

/**********************************************************/

<?php

class inStance{

// 保存类实例的静态变量

private static $_instance;

// 构造函数 声明 为 非public

private function __construct(){

}

// 访问这个实例的 公共的 静态方法

public static function getInstance(){

// 判断 类是否被实例

if (!(self::$_instance instanceof self)) {

// 静态变量 = 实例化类本身

self::$_instance = new self();

}

return self::$_instance;
}

// 自己定义一个方法

public function test(){

echo "test";

}

// 防止用户复制 对象实例

public function __clone(){

// trigger_error() 函数创建用户定义的错误消息

trigger_error('Clone is not allow' ,E_USER_ERROR);

}

}

// 这个写法会出错,因为构造方法被声明为private

$test = new Example;

// 下面将得到inStance类的单例对象

$test = inStance::getInstance();

$test->test();

// 复制对象将导致一个E_USER_ERROR.

$test_clone = clone $test;

?>

原文地址:https://www.cnblogs.com/laowenBlog/p/5439985.html