【问题标题】:Dealing with Singleton class instance处理 Singleton 类实例
【发布时间】: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


【解决方案1】:

代码对我来说看起来不错,虽然我还没有测试过。但是,我建议您创建一个私有或受保护(但不是公共)构造函数,因为您只想能够从您的类内部创建一个实例(在 DataManager::singleton() 中)

【讨论】:

  • 很奇怪,我在 macosx 上使用了 MAMP。显然 MAMP 不能按我想要的方式工作。我现在在 Windows 机器上测试了它,安装了 Xampp,它确实工作正常。我正在考虑不使用单例.. 感谢 arjan,感谢 netcoder 和 gordon!
猜你喜欢
  • 2015-04-02
  • 2015-01-25
  • 2018-06-30
  • 1970-01-01
  • 2017-04-28
  • 2019-07-14
  • 1970-01-01
  • 2014-01-20
  • 1970-01-01
相关资源
最近更新 更多