用PHP来构造一个单例类
<?php
class Single {
private static $self;
final protected function __construct() {
}
final public static function get_self() {
if (Single::$self instanceof Single)
return Single::$self;
Single::$self = new Single();
return Single::$self;
}
function __clone() {
trigger_error('对不起, 不允许克隆', E_USER_WARNING);
}
}
$s = Single::get_self();
$s1 = Single::get_self();
var_dump($s == $s1);
最终结果
可以看到,两个对象实例是相等的。说明,这两个对象全部指向了同一个类。从而达到,单例的效果。