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!