php设计模式之单例模式使用示例_php实例

WBOY
Release: 2016-05-17 08:50:38
Original
793 people have browsed it

以下为单例模式代码:

复制代码 代码如下:

class EasyFramework_Easy_Mysql{
    protected static $_instance = null;
    private function __construct(){

    }
    public static function getInstance(){
        if (self::$_instance === null){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    protected function __clone(){

    }

}

$x = EasyFramework_Easy_Mysql::getInstance();

var_dump($x);


?>


/*
 * 1.第一步:
 * 既然是单例,也就是只能实例化一次,也就代表在实例化时
 * 不可能使用new关键字!!!!
 * 在使用new关键字时,类中的构造函数将自动调用。
 * 但是,如果我们将构造函数的访问控制符设置为protected或private
 * 那么就不可能直接使用new关键字了!!!
 * 第二步:
 * 无论protected/private修饰的属性或方法,请问在当前类的
 * 内部是否可以访问?---> 可以
 * 第三步:
 * 现在我们根本没有办法得到对象(因为你不能使用new关键字了),
 * 第四步:静态成员(包括属性或方法)在访问时,只能通过
 * 类名称::属性()
 * 类名称::方法()
 * 第五步:如果我现在存在一个静态方法--> getInstance()
 * 那么在调用时就应写成
 * $object = EasyFramework_Easy_Mysql::getInstance()
 * 如果,getInstance()方法可以得到唯一的一个对象
 * 也就代表是所谓的单例模式了!!!
 * 第六步,怎么让getInstace()只得到一个对象呢?
 * 既然要得到对象,那么肯定是:
 * $variabl = new ????();
 * 我们又知道静态属性的值是可以所有的对象来继承的!!!
 * 静态成员是属于类的,而非对象的!
 * 所以:
 * 第七步:声明一个静态的属性,用其存储实例化的对象
 * protectd static $_instance
 *
 * 并且初始值为null
 * 那么我在调用getInstance()方法时,只需要判断其值是否为空即可
 *
 * public static function getInstance(){
 *     if(self::_instance === null){
 *      self::_instance = new self();
 *  }
 *  return self::_instance;
 * }
 * 在实例时,一定是这样写:
 * $x = EasyFramework_Easy_Mysql::getInstance();
 * 在第一时调用时,类的$_instance这个静态属性值为null,
 * 那么也就代表,getInstance()方法的判断条件为真了,
 * 也就意味着
 * self::$_instance这个成员有了值了!!!
 * 并且还返回这个值
 * $y = EasyFramework_Easy_Mysql::getInstance();
 * 在第二次或第N次调用时,self::$_instance已经有了值了
 * 也就代表getInstance()方法的条件为假了!!!
 * 也就代表其中的程序代表不可能执行了!!!
 * 也就代表将直接返回以前的值了!!!
 *
 *
 *
 * */

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!