在单例类中重新初始化常量

时间:2011-07-23 09:38:59

标签: php oop singleton

我想知道是否有可能以某种方式“重新初始化”单例类中的常量。

例如:

class Foo {

    public static $instance = null;    

    private $status = null;

    private function __construct() { }

    public static function getInstance() {
        if(!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
            self::$instance->setUp();
        }

        return self::$instance;
    }

    // Function that will change the $status variable
    private function bar() {

        ...

        $this->status = TRUE;
    }

    private function setUp() {

        ...

        $this->bar();

        define("HELLO", $this->status);

    }

    public function baz() {

        ...

        $this->bar();
    }

}

所以如果我打电话给 $ foo-> baz(),它会以某种方式重写 HELLO 常量。

1 个答案:

答案 0 :(得分:1)

是否为单例类,常量是全局的,常量。一旦define d,它们就不会被定义或改变。如果需要更改值,请使用变量。在这种情况下,可能是static类变量。


根据你的评论判断,你似乎对定义常数时有误解。

可能的:

define('FOO', rand());

每次执行脚本时,常量将具有不同的值 (每次访问页面时)。

不可能:

define('FOO', 'bar');
define('FOO', 'baz');

在同一请求期间无法更改