我在PHP中创建了一个单例类:
<?php
class DataManager
{
private static $dm;
// The singleton method
public static function singleton()
{
if (!isset(self::$dm)) {
$c = __CLASS__;
self::$dm = new $c;
}
return self::$dm;
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function test(){
print('testsingle');
echo 'testsingle2';
}
function __get($prop) {
return $this->$prop;
}
function __set($prop, $val) {
$this->$prop = $val;
}
}
?>
当我尝试在index。php中使用这个类时:
<?php
include('Account/DataManager.php');
echo 'test';
$dm = DataManager::singleton();
$dm->test();
echo 'testend';
?>
我得到的唯一回显是'test',单例类中的函数test()似乎从未被调用过。此外,index.php末尾的'testend'永远不会被调用。
是否有一个错误在我的单例类?
代码看起来不错,虽然我还没有测试过。然而,我建议你创建一个私有的或受保护的(但不是公共的)构造函数,因为你只希望能够从你的类内部创建一个实例(在DataManager::singleton()
)