我知道这是愚蠢的,但我无法弄清楚。 我在MVC框架的上下文中发现了一些类似的questions。 这就是我的情况,因为我使用的是CodeIgniter。变量作用域:require_once不加载我的变量,但是需要做的事
我有一个文件questions.php
(这是包含在一个视图):
require_once '../site_init.php';
var_dump($siteVars);
// shows null and a Notice: Undefined variable: siteVars
// but the ABSPATH constant is showing as defined!
var_dump(ABSPATH);
// shows string 'c:\wamp\www\sitename'
require '../site_init.php';
var_dump($siteVars);
// correctly dumps the content of siteVars array
,并应处处包含的文件site_init.php
因为它拥有我的站点范围的配置值:
if (!defined('ABSPATH'))
define('ABSPATH', dirname(__FILE__) . '/');
/** Site-wide sitevars */
$siteVars = array();
// set to true in develop environment
$siteVars['debug'] == false;
我知道The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again
但是,当我使用require_once
时,我收到一条通知,内容为Undefined variable: siteVars
,而使用require
时,所有按预期工作。但是,正如您在上面的代码中看到的那样,该常量显示为已定义,尽管它们都在同一个文件中定义。 PHP manual:Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope.
print_r(get_included_files());
显示site_init.php被包含在require_once之前,所以我不应该再次需要(_once)它。
它必须与变量作用域有关。如果我使用global $siteVars
,它可以正常工作,而不需要require
这个文件,但是有人可以解释为什么会发生这种情况?我是CodeIgniter的新手。我可以看到只有一个入口点(主index.php文件),这是基本文件($_SERVER['PHP_SELF']
)。
理想情况下,我也想知道如何解决这个问题,而不使用global
或require
。
UPDATE: 文件结构似乎是以下(这是一个项目,我只是工作,我不是原来的开发商):
控制器
welcome.php
负载(include_once)的文件X在CodeIgniter应用程序文件夹结构之外(CI应用程序是较大站点的管理员部分)。文件X include_once
site_init.php
文件控制器
welcome.php
负荷的观点$this->load->view('template', $data);
这是相当多了。希望这是解决方案的关键。
http://stackoverflow.com/a/2418514/3599549。页面早已包含在内吗? – Krii
很奇怪,我在这里用2个文件测试过,使用require和require_once,两次都成功了。我能够打印变量的内容。 –
什么是你的PHP版本?我觉得Codeigniter与此无关。看起来像一个命名空间问题,但它很奇怪,所以说...... –