PHP static not so static

早过忘川 提交于 2020-01-16 18:15:51

问题


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 on this, thanks!


回答1:


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.




回答2:


because on every page load all memory is wiped ?




回答3:


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


来源:https://stackoverflow.com/questions/4977162/php-static-not-so-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!