I noticed strange behavior with singlots in PHP, there is no better way to explain this, but with an example.
Let's say I have the following singleton class:
class Singleton { protected function __construct() { // Deny direct instantion! } protected function __clone() { // Deny cloning! } public static function &Instance() { static $Instance; echo 'Class Echo'.PHP_EOL; var_dump($Instance); if (!isset($Instance)) { $Instance = new self; } return $Instance; } }
And the following function:
function Test($Init = FALSE) { static $Instance; if ($Init === TRUE && !isset($Instance)) { $Instance =& Singleton::Instance(); } echo 'Function Echo'.PHP_EOL; var_dump($Instance); return $Instance; }
And when I use the following:
Test(TRUE); Test(); Singleton::Instance();
Output:
Class Echo NULL Function Echo object(Singleton)#1 (0) { } Function Echo NULL Class Echo object(Singleton)#1 (0) { }
As you can see, the stored link inside the function is lost after execution, even if the variable is static. Also note that the static variable inside the class method works fine.
Is this normal, or am I doing something wrong?
source share