Kevin
Kevin

Reputation: 5694

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

Upvotes: 0

Views: 634

Answers (3)

netcoder
netcoder

Reputation: 67695

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.

Upvotes: 8

Explosion Pills
Explosion Pills

Reputation: 191729

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

Upvotes: 3

Rasmus Styrk
Rasmus Styrk

Reputation: 1346

because on every page load all memory is wiped ?

Upvotes: 9

Related Questions