}
static
public
function
getInstance()
{
if
(!self::
$_instance
instanceof
self)
{
//echo 'lgh-big';
self::
$_instance
=
new
self;
}
else
{
//for testing only
//echo 'gdc-xiaoairener';
}
return
self::
$_instance
;
}
public
function
getHeight()
{
echo
$this
->height;
}
public
function
getAge()
{
echo
$this
->age;
}
}
function
testInstance()
{
People::getInstance()->getAge();
}
//begin to use the class
$lgh
= People::getInstance();
$lgh
->getHeight();
echo
'<br />';
testInstance();
?>
优点:单例模式可以避免大量的
new
操作,因为每一次
new
操作都会消耗内存资源和系
统资源
缺点:在 PHP
中,所有的变量无论是全局变量还是类的静态成员,都是 页面级的,每次
页面被执行时,都会重新建立新的对象,都会在页面执行完毕后被清空,这样似乎 PHP
单例模式就没有什么意义了,所以 PHP
单例模式我觉得只 是针对单次页面级请求时出现
多个应用场景并需要共享同一对象资源时是非常有意义的。
Why–为什么要使用 PHP 单例模式?
PHP 的一个主要应用场合就是应用程序与数据库打交道的应用场景,所以一个应用中会