復制代碼 代碼如下:
<?php
/**
* 單例模式
*
* 保證一個類僅有一個實例,並提供一個訪問它的全局訪問點
*
*/
class Singleton
{
static private $_instance = null;
private function __construct()
{
}
static public function getInstance()
{
if(is_null(self::$_instance)) {
self::$_instance = new Singleton();
}
return self::$_instance;
}
public function display()
{
echo "it is a singlton class function";
}
}
// $obj = new Singleton(); // 聲明不能成功
$obj = Singleton::getInstance();
var_dump($obj);
$obj->display();
$obj1 = Singleton::getInstance();
var_dump(($obj === $obj1));