PHP设计模式二-------单例模式

1.单例模式的介绍

意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点;

主要解决:一个全局使用的类频繁地创建与销毁。

关键代码:构造函数是私有的,克隆方法也是私有的。

1.1 懒汉式//1 懒汉式


class single{

    private static $instance;
    private function __construct(){

    }
    private function __clone(){

    }
    public static function getInstance(){
        if ( empty( self::$instance ) ){
            self::$instance = new single();
      // 1 self::$instance = new self();  #实例化的是他本身 和single()相同
      // 2 self::$instance = new static(); #实例化的是调用者,继承中和self有区别
        }
        return self::$instance;
    }

    public function getName(){
        return 'vic';
    }
}


$single = single::getInstance();

var_dump($single->getName());

2. 饿汉式

php是不支持的。

class Single{

    private  $instance = new Single();
    private function __construct(){

    }
    private function __clone(){

    }
    public static function getInstance(){

        return self::$instance;
    }

    public function getName(){
        return 'vic';
    }
}


$single = Single::getInstance();

var_dump($single->getName());

程序直接报错:php7:Fatal error: Constant expression contains invalid operations 

         PHP5:Parse error: syntax error, unexpected 'new'

php的属性赋值必须是常量,new single() 不是一个常量,所以饿汉式在php中不可以使用;php7是提前编译的,所以会在编译阶段直接报错;提示非常数;而php5中,在执行的时报错,提示无效new ;

原文地址:https://www.cnblogs.com/myvic/p/7988223.html