2010-04-27 24 views
0

我想要做的是在Word Press主題中包含我的一個PHP腳本。問題是,在包含腳本文件後,我無法在主題文件的函數內訪問腳本文件中聲明的變量。

我已經在主題文件夾中創建了一個新文件,並添加了與header.php相同的代碼,並且如果我打開該文件,它的工作原理就好了。據我所知,這是Word Press的相關內容。的

/other/path/wordpress/wp-content/themes/theme-name/header.php // this is broken 
/other/path/wordpress/wp-content/themes/theme-name/test.php // this works 

/var/www/vhosts/domain/wordpress/ ->(symlink)-> /other/path/wordpress/ 
               /other/path/wordpress/wp-content/themes/theme-name/header.php 
/var/www/vhosts/domain/include_file.php 

內容:/var/www/vhosts/domain/include_file.php

$global_var = 'global'; 
print_r($GLOBALS); // if I open this file directly this prints globals WITH $global_var; 
        // if this file is included in header this prints all the WP stuff WITHOUT $global_var; 

內容:/其它/路/ WordPress的/可溼性粉劑內容/主題/主題名稱/頭.php 需要'/path/to/include_file.php';

print $global_var; // this prints 'global' as expected 
function test() 
{ 
    global $global_var; 
    print $global_var; // this is NULL 
} 
test(); 
print_r($GLOBALS); // this prints all the WP stuff WITHOUT $global_var in it 
+1

globals是不好的做法,不要用它 – silent 2010-04-27 11:44:38

+0

我需要使用它作爲自動加載器的函數並自動接收它的參數。全球是獲取數據的最簡單方式。 – Brayn 2010-04-27 12:06:02

回答

4

我不提倡使用$GLOBALS,但無論如何...使用定義變量:

$GLOBALS['varname'] = 'value'; 

這應該工作。我懷疑你實際上並不像你認爲的那樣在全球範圍內。該文件可能正在被一個函數包含,在這種情況下,你在函數範圍內。

+0

我剛剛找到答案並且回覆發佈了答案。但你是對的,我不在正確的範圍內。 謝謝! – Brayn 2010-04-27 14:59:17