2011-12-30 115 views
0

我有一個名爲PHP函數變量

chewbacca() { 
    include('external.php'); 
    echo $lang[1]; 
    ... 
    } 

文件external.php包含了所有的$ LANG陣列功能。但是,由於我必須執行數千次函數,因此我只想包含一次文件。如果我include_once('external.php');在函數之前,如何在我的函數中使用$ lang數組變量,而不必在每次使用之前編寫「global」?

回答

1

除非我誤解了以後的內容,否則在每次使用之前不需要寫global,只需在函數的開頭使用它即可。

include('external.php'); 

chewbacca() { 
    global $lang; 
    echo $lang[1]; 
    ... 
} 
2

也許將它作爲參數傳遞?

<?php 

include 'external.php'; 

function chewbacca($lang_array){ 
    echo $lang_array[1]; 
    //... 
} 

編輯:

你可以做以下太:

在external.php:

<?php 

return array(
    'foo', 
    'foobar', 
    'bar', 
); 

在index.php文件:

<?php 

function chewbacca($lang_array){ 
    echo $lang_array[1]; 
    //... 
} 

$foo = include 'external.php'; 
chewbacca($foo); 

EDIT2: 當然現在您可以使用include_once,但是我會推薦require_once,因爲如果include發生故障並且腳本應該停止並出現錯誤,您將不會有陣列。

+1

哇,我得到了我的認證工程師證書,我從來沒有見過或使用過「$ foo = include(file)」。這真的有用嗎?我認爲include是一種語言結構,它不會返回任何內容...... – 2011-12-30 17:02:52

+0

每天的上學日:-) – cmbuckley 2011-12-30 17:05:03

+0

@Paul哦,我剛剛讀過它,如果您在包含文件中「返回」某些內容,它將返回它而不是整合到當前位置的代碼...不錯 – 2011-12-30 17:05:20

0

如果我正確地理解了你,請在使用它之前嘗試將它傳遞給本地範圍;這樣你只需要在函數內部使用全局範圍。

1

簡單的說,你不能......

您有幾種方法可以做到這一點:

路#1

global $lang; 
include('external.php') 
function chewbacca(){ 
    global $lang; 
    echo $lang[1]; 
} 

路#2

function chewbacca(){ 
    include('external.php') 
    echo $lang[1]; 
} 

路#3

function chewbacca(){ 
    static $lang; 
    if(!is_array($lang)){ include('external.php'); } 
    echo $lang[1]; 
} 

路#4

include('external.php') 
function chewbacca($lang){ 
    echo $lang[1]; 
} 
chewbacca($lang); 

好運

PS:另一種方法是使用一類負荷的字符串類當它被創建(在構造函數中)並從$ this-> lang訪問語言字符串時...

1

靜態類也是一個解決方案。

class AppConfiguration { 
    static $languages = array(
     'en' => 'English' 
    ); 
} 

function functionName($param) { 
    $lang = AppConfiguration::$languages; 
} 

require_once該文檔中的類,就是它。

+0

+1:這是一個更好的解決方案。 – cmbuckley 2011-12-30 17:08:43