Question

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?

Was it helpful?

Solution

How about having extract2() return a clean array and run extract() on its result?

extract(extract2())

I don't know for sure, but I think extract()s functionality is magic and difficult to replicate.

OTHER TIPS

I'm sorry if this sounds rude, but I just don't see the need for this.

Why, oh why, would you want to do this? What you're attempting to do is more effort and just simply more annoying than to use the array itself.

you should take a look at this comment @ php doc This is what you need I think

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top