require_once to global scope within a function

Tomas picture Tomas · Jan 25, 2012 · Viewed 17.3k times · Source

It seems that if require_once is called within function, the included file doesn't extend the global variable scope. How to require_once a file to global scope from within a function?

What I'm trying to do is some dynamic module loader:

function projects_init()
{
        ...
        foreach ($projects as $p) {
                require_once($p['PHPFile']);

                $init_func = $p['init'];
                if ($init_func)
                        $init_func();
        }
}

If it is not possible to use require_once that way, what is the simplest solution for this? (Please no heavy frameworks.)

EDIT: it should also work for PHP 5.2.

Answer

Tomas picture Tomas · Jan 26, 2012

To summarize all the information:

  1. functions are not an issue, they will be global anyway this way

  2. for global variables, there are 2 options:

    • declare them as global in the included file
    • declare them as global in that function (projects_init() in my case)