单例模式

单例模式的定义:保证一个类只有一个实例,并提供一个访问它的全局访问点

class Singleton
{
    //创建静态私有的变量保存该类对象
    static private $instance;

    //防止使用new直接创建对象
    private function __construct(){}

    //防止使用clone克隆对象
    private function __clone(){}

    static public function getInstance()
    {
        //判断$instance是否是Singleton的对象,不是则创建
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function test()
    {
        echo "我是一个单例模式";
    }
}

$sing = Singleton::getInstance();
$sing->test();
$sing2 = new Singleton(); //Fatal error: Uncaught Error: Call to private Singleton::__construct() from invalid context in
$sing3 = clone $sing; //Fatal error: Uncaught Error: Call to private Singleton::__clone() from context

  

原文地址:https://www.cnblogs.com/zh718594493/p/12090502.html