dave dave - 4 months ago 7
PHP Question

How do I use variables from another PHP include file in a function?

I have this PHP include file that has all the variables I'll be using. How can I use all those variables in another file in a function, without declaring them again as global in that function?

Answer

You can access all variables of the global scope with:

$GLOBALS['varname']

To avoid the use of the $GLOBALS all the time you can "globalize" variables automatically:

Place this in your function to "import" all variables:

foreach($GLOBALS as $key=>$val){
    if(!isSuperGlobal($key))
        global $$key;
}

And put this help function somewhere else outside your function

function isSuperGlobal($name){
    switch($name){
        case 'GLOBALS':
        case '_SERVER':
        case '_GET':
        case '_POST':
        case '_FILES':
        case '_COOKIE':
        case '_SESSION':
        case '_REQUEST':
        case '_ENV':        return true;    break;
        default:            return false;   break;
    }
}