note 105851 deleted from language.variables.scope by googleguy
| From: | googleguy@php.net | Date: | Tue, 22 Oct 2013 12:16:28 +0000 |
| Subject: | note 105851 deleted from language.variables.scope by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-197126@lists.php.net to get a copy of this message | ||
Note Submitter: dr_dazzit at yahoo dot co dot uk
----
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.