note 105851 added to language.variables.scope

From: Date: Tue, 20 Sep 2011 09:33:18 +0000
Subject: note 105851 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-183288@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. <? 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. ---- Server IP: 87.124.126.117 Probable Submitter: 86.150.166.223 (proxied: 86.150.166.223) ---- Manual Page -- http://www.php.net/manual/en/language.variables.scope.php Edit -- https://master.php.net/note/edit/105851 Del: integrated -- https://master.php.net/note/delete/105851/integrated Del: useless -- https://master.php.net/note/delete/105851/useless Del: bad code -- https://master.php.net/note/delete/105851/bad+code Del: spam -- https://master.php.net/note/delete/105851/spam Del: non-english -- https://master.php.net/note/delete/105851/non-english Del: in docs -- https://master.php.net/note/delete/105851/in+docs Del: other reasons-- https://master.php.net/note/delete/105851 Reject -- https://master.php.net/note/reject/105851 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#183288) next »