【发布时间】:2011-04-28 15:46:47
【问题描述】:
我在 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”也从未被调用过。
我的单例类有错误吗?
【问题讨论】:
-
无法重现这个...示例代码在我的机器上运行。
-
如果您只访问
echo "test";,您可能需要打开错误报告。 -
我认为处理单例类的最好方法是根本不处理它们。 ;)
标签: php oop singleton echo data-management