处理 Singleton 类实例
我在 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”从未被调用过。
我的单例类有错误吗?
I created a singleton class in 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;
}
}
?>
Now when I try to use this class in my index.php:
<?php
include('Account/DataManager.php');
echo 'test';
$dm = DataManager::singleton();
$dm->test();
echo 'testend';
?>
the only echo I get, is 'test', the function test() in the singleton class, is never called so it seems. Also the 'testend' at the end of the index.php is never been called.
Is there an error in my singleton class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管我还没有测试过,但该代码对我来说看起来不错。不过,我建议您创建一个私有或受保护(但不是公共)构造函数,因为您只想能够从类内部创建一个实例(在
DataManager::singleton()
中)The code looks fine to me, although I haven't tested it. I would however advise you to create a private or protected (but not public) constructor, since you only want to be able to create an instance from inside your class (in
DataManager::singleton()
)