我正在调用一个名为ajax.php的文件(从我的浏览器进行测试)
ajax.php require_once delete.php
delete.php require_once no_direct.php
delete.php是这样启动的:
$allowed = array('group'=>'admin');
require_once(ASSETS.'/no_direct.php'); //Yes, ASSETS is defined and no_direct is being included.
在no_direct.php中,我尝试:
var_dump($allowed)
而我一直保持NULL。
发生这种情况是因为我们在ajax.php的require_once函数内部运行,并且$ allowed的范围推回到GLOBAL范围,不允许我从no_delete.php访问它吗?
我在这里看:PHP variable defined in 'parent' file not recognized in 'required' file,只是为了勤奋。
我确定我可以使用GLOBAL关键字解决此问题,但我希望对此有所说明。 PHP作用域文档似乎没有为我回答这个问题。
并没有像其他情况那样将其包装在另一个函数中。
最佳答案
在将值分配给require_once(ASSETS.'/no_direct.php');
之前,您是否已经有机会调用$allowed
?
require_once(ASSETS.'/no_direct.php');
...
$allowed = array('group'=>'admin');
require_once(ASSETS.'/no_direct.php');
在这种情况下,脚本
no_direct.php
不应该输出$allowed
。输出将是:
Notice: Undefined variable: allowed in D:\wampserver\www\gim\no_direct.php on line 2
NULL
ps。我的测试文件在wamp中的localhost上有我的路径
关于php - 所需文件中的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5530911/