note 105851 modified in language.variables.scope by danbrown

From: Date: Tue, 20 Sep 2011 11:25:30 +0000
Subject: note 105851 modified in language.variables.scope by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-183293@lists.php.net to get a copy of this message
Functions are always global. I've had fun and games in the past with the global keyword with nested functions. So for teleporting variables between functions I've occasionally adopted this simple method. <?php function &teleport($vars = null){ static $toSave = array(); if($vars){ foreach($vars as $k=>&$v) $toSave[$k] = $v; } return($toSave); } function myFuncA(){ extract(teleport(),EXTR_REFS); $a = array('a'=>1,'b'=>2); $b = "An arbitrary value of no consequence\n"; teleport(array('a'=>$a,'b'=>$b)); } function myFuncB(){ extract(teleport(),EXTR_REFS); $b = "Now this is of Consequence\n"; $c = "Another of Consequence\n"; teleport(array('c'=>$c)); } function myFuncC(){ extract(teleport(),EXTR_REFS); // $a,$b,$c are now in current scope print_r(get_defined_vars()); print_r($a); echo($b); echo($c); } myFuncA(); myFuncB(); myFuncC(); ?> Purists might shout something about "USE A CLASS" etc... Maybe but sometimes you might not want to or need to. --was-- Functions are always global. I've had fun and games in the past with the global keyword with nested functions. So for teleporting variables between functions I've occasionally adopted this simple method. <? function &teleport($vars = null){ static $toSave = array(); if($vars){ foreach($vars as $k=>&$v) $toSave[$k] = $v; } return($toSave); } function myFuncA(){ extract(teleport(),EXTR_REFS); $a = array('a'=>1,'b'=>2); $b = "An arbitrary value of no consequence\n"; teleport(array('a'=>$a,'b'=>$b)); } function myFuncB(){ extract(teleport(),EXTR_REFS); $b = "Now this is of Consequence\n"; $c = "Another of Consequence\n"; teleport(array('c'=>$c)); } function myFuncC(){ extract(teleport(),EXTR_REFS); // $a,$b,$c are now in current scope print_r(get_defined_vars()); print_r($a); echo($b); echo($c); } myFuncA(); myFuncB(); myFuncC(); ?> Purists might shout something about "USE A CLASS" etc... Maybe but sometimes you might not want to or need to. http://php.net/manual/en/language.variables.scope.php

« previous php.notes (#183293) next »