我知道這是愚蠢的,但我無法弄清楚。 我在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與此無關。看起來像一個命名空間問題,但它很奇怪,所以說...... –