开发者

PHP static not so static

I've noticed that the keyword static in PHP is not that static at all.

Lets say Elmo is my singleton:

class Elmo
{
    private static $instance;

    private function __construct()
    {
        echo 'Elmo says constructor\n';
    }

    public static function getInstance()
    {
        if (!isset(self::$instance))
            self::$instance = new Elmo();

        return self::$instance;
    }

    public function boo()
    {
        echo 'Elmo says boo!\n';
    }
}

And the following file is just a regular .php script.

<?php

    Elmo::getInstance()->boo();
    Elmo::getInstance()->boo();

    // Output:
    // Elmo says constructor
    // Elmo says boo!
    // Elmo says boo!

?>

Every new page Elmo gets re-constructed. Why don't subsequent pages have the following output?

<?php

    // Output:
    // Elmo says boo!
    // Elmo says boo!

?>

I hope someone can enlighten me 开发者_JAVA技巧on this, thanks!


because on every page load all memory is wiped ?


Static scoping does not mean it will stay in memory forever, it means that the variable operates outside the program call stack, and will persist during the execution of the script. It is still cleared after the program ends.


This is because every time you do a page load it runs {main} separately. This would be like running a java program two separate times and the static property not being retained. Elmo::$instance will only remain instantiated in the context of the same script. If you want it to work across page loads, you can serialize it in the session (or DB) and check this instead of $instance each time:

const SESSION = 'session';
public static function inst() {
   !isset($_SESSION[self::SESSION]) and self::init();
   self::$inst = $_SESSION[self::SESSION];
   return self::$inst;
}
private static function init() {
   $_SESSION[self::SESSION] = new self;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜