I have a function, which is a safer way to extract variables than extract().
Basically you just specify which variable names are to be pulled out of an array.
The problem is, how do you insert those variables into the "current symbol table" like extract() does? (ie. the local variable scope within a function).
I can only do this by making them global variables for now:
/**
* Just like extract(), except only pulls out vars
* specified in restrictVars to GLOBAL vars.
* Overwrites by default.
* @param arr (array) - Assoc array of vars to extract
* @param restrictVars (str,array) - comma delim string
* or array of variable names to extract
* @param prefix [optional] - prefix each variable name
* with this string
* @examples:
* extract2($data,'username,pswd,name','d');
* //this will produce global variables:
* // $dusename,$dpswd,$dname
*/
function extract2($arr,$restrictVars=null,$prefix=false)
{
if(is_string($restrictVars))
$restrictVars=explode(",",$restrictVars);
foreach ($restrictVars as $rvar) {
if($prefix) $varname="$prefix$rvar";
else $varname=$rvar;
global ${$varname};
${$varname}=$arr[$rvar];
}
}
Usage:
extract2($_POST,"username,password,firstname");
echo "Username is $username";
Where things dont work too well... inside a function:
function x($data)
{
extract2($data,"some,var,names,here");
//now the variables are are global, so you must:
global $some,$var,$names,$here;
}
Any idea how to avoid the global, but instead insert the var into the local var scope?