使全局变量可用于函数中的包含文件

I need to include files within a function, and files use lots of variables defined earlier in the script. Using global is not an option because it is impossible to say which variables will be used in included files. The only one real solution is to make all global variables accessible in function, something like:

     function finc($file)
    {

        foreach($GLOBALS as $k=>$v)
        {
            $$k=$v;
        } 
        include $file;
   }

but it won't be good when using lots of files with lots of variables, so is there any better way to do it?

there is no good answer for that problem. only an advice. use objects... what you are doing is possible but in my opinion a very bad solution because you are defining all globals. there is however a more efficient way to do that: extract($GLOBALS), but it would be better to use $GLOBALs['whatever'] in your included scripts...

Beware: you're really importing all global variables.

extract($GLOBALS);

If you are doing this for templateing then you shall provide the template only a "context", not all global variables. Simply specify an array of variables that should be accessible in the template and extract them.

If it isn't templateing what you do, but routing you should think about returning the file name to include:

include getPathForPage('home');