0

我在 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”也从未被调用过。

我的单身课程有错误吗?

4

1 回答 1

1

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

于 2011-04-28T16:14:48.710 回答