|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2004-03-26 15:20 UTC] leonel at nied dot unicamp dot br
Description: ------------ I tried to implement a class with the Singleton pattern. However, static variables do not seem to tie to the class, but rather to the instance of the class. Looking at bug 16245 http://bugs.php.net/bug.php?id=16245&edit=2 I see that Mr. Flying and I have sort of 'exchanged' bugs. He got the result I expected and I got the result he expected. Notice 2 things: first, he assigned a primitive type to his variable, whereas my variable holds an object; second, his variable is declared inside the function, and mine is declared inside the class. Reproduce code: --------------- <?php class IntegerFactory { private static $int = NULL; function __construct() {} public function getInstance() { if ( !isset($this->int) ) { echo 'null !', "\n"; $this->int = new IntegerFactory; } return $this->int; } } $tmp1 = new IntegerFactory; $d1 = $tmp1->getInstance(); var_dump($d1); $tmp2 = new IntegerFactory; $d2 = $tmp2->getInstance(); var_dump($d2); $d3 = $tmp1->getInstance(); var_dump($d3); ?> Expected result: ---------------- null ! object(IntegerFactory)#2 (0) { } object(IntegerFactory)#2 (0) { } object(IntegerFactory)#2 (0) { } Actual result: -------------- null ! object(IntegerFactory)#2 (0) { } null ! object(IntegerFactory)#4 (0) { } object(IntegerFactory)#2 (0) { } PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 22 09:00:01 2025 UTC |
Works well using this code: kasedebian:/var/www# cat test.php5 <?php class IntegerFactory { private static $int = NULL; function __construct() {} public function getInstance() { if ( !isset(IntegerFactory::$int) ) { echo 'null !', "\n"; IntegerFactory::$int = new IntegerFactory; } return IntegerFactory::$int; } } $tmp1 = new IntegerFactory; $d1 = $tmp1->getInstance(); var_dump($d1); $tmp2 = new IntegerFactory; $d2 = $tmp2->getInstance(); var_dump($d2); $d3 = $tmp1->getInstance(); var_dump($d3); ?>