note 88570 modified in language.variables.scope by danbrown

From: Date: Sat, 31 Jan 2009 18:03:12 +0000
Subject: note 88570 modified in language.variables.scope by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-150036@lists.php.net to get a copy of this message
Like functions, if you declare a variable in a class, then set it as global in that class, its value will not be retained outside of that class either. <?php class global_reference { public $val; public function __construct () { global $var; $this->val = $var; } public function dump_it () { debug_zval_dump($this->val); } public function type_cast () { $this->val = (int) $this->val; } } $var = "x"; $obj = new global_reference(); $obj->dump_it(); $obj->type_cast(); echo "after change "; $obj->dump_it(); echo "original $var\n"; ?> The work-around is of course changing the assignment in the constructor to a reference assignment as such: <?php //.... $this->val = &var; //.... ?> If the global you're setting is an object then no reference is necessary because of the way PHP deals with objects. If you don't want to reference to the same object however you can use the clone keyword. <?php //... global $Obj; $this->obj_copy = clone $Obj; //... ?> [EDIT BY danbrown AT php DOT net: Merged all thoughts and notes by this author into a single note.] --was-- in response to the issue ddarjany at yahoo dot com raised: Just to clarify; the same goes for classes. <?php class global_reference { public $val; public function __construct () { global $var; $this->val = $var; } public function dump_it () { debug_zval_dump($this->val); } public function type_cast () { $this->val = (int) $this->val; } } $var = "x"; $obj = new global_reference(); $obj->dump_it(); $obj->type_cast(); echo "after change "; $obj->dump_it(); echo "original $var\n"; ?> The work-around is of course changing the assignment in the constructor to a reference assignment as such: <?php //.... $this->val = &var; //.... ?> http://php.net/manual/en/language.variables.scope.php

« previous php.notes (#150036) next »