php - Static variable inside function can't hold reference to singleton -


i've noticed weird behavior singletons in php there's no better way explain example.

let's have 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 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 use following:

test(true); test(); singleton::instance(); 

the output is:

class echo null function echo object(singleton)#1 (0) { } function echo null class echo object(singleton)#1 (0) { } 

as can see saved reference inside function lost after execution though variable static notice static variable inside class method working fine.

is supposed normal or i'm doing wrong?

this behaviour documented:

the zend engine 1, driving php 4, implements static , global modifier variables in terms of references. example, true global variable imported inside function scope global statement creates reference global variable. can lead unexpected behaviour.

this behaviour hasn't changed since ze1 , solution not assign reference static variable, so:

$instance = singleton::instance(); 

update

i've simplified issue below:

function test2($init = false, $value = null) {   static $test;    if ($init) {     $test =& $value;   }    var_dump($test); }  $v = 1;  test2(true, $v); test2(); 

output:

int(1) null 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -