require_once to global scope within a function

那年仲夏 提交于 2019-12-19 05:18:39

问题


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.


回答1:


The above answer is right, you can use global to get what you need. In the included file just declare the variables global at the beginning of the file, this way the code will run in the function scope but it will change the global variables(yes, you have to be careful and declare everything you need to change as global but it should work), example:

function a() {
     require_once("a.php");
}
a();
echo $globalVariable;

and in the a.php file:

global $globalVariable;
$globalVariable="text";



回答2:


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)



回答3:


Functions are not an issue (ref):

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

About global variables: As in an existing question regarding the scope of require and the like, the scope is defined where the use is. If you need something else, there are numerous answers (my take) that show how to deal with global variables, most making use of get_defined_vars.




回答4:


You can use global to put a variable in the global scope.

http://php.net/manual/en/language.variables.scope.php



来源:https://stackoverflow.com/questions/9002188/require-once-to-global-scope-within-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!