开发者

Reinitialize constant inside a singleton class

I wonder if it is possible to "reinitialize" somehow a constant within a singleton class.

For example:

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();
    }

}

So if i call $foo->baz() it will somehow rewrite my HELLO constant.


Singleton class or not, constants are global and constant. Once defined they can't be undefined or altered. If you need to alter the value, use a variable. In this case, probably a static class variable.


Judging by your comments, you seems to have a misconception of when constants are defined.

Possible:

define('FOO', rand());

The constant will have a different value each time the script is executed (each time a page is visited).

Not possible:

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

Constants can't be changed during the same request.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜