2014-11-04 43 views
0

我有兩個不同的.php文件,第一個被稱爲get_data.php,看起來像這樣:混亂與PHP範圍,而使用功能

<?php 
    ... 

    $current_date = date("Y-m-d H:i:s"); 

    $total_sales = 35; 
    $total_revenue = 12; 

    $this_month_sales = 3; 
    $this_month_revenue = 7; 

    $last_month_sales = 2; 
    $last_month_revenue = 5; 

    ... 
?> 

現在,第二個文件我用被稱爲index.php,和在向上的index.php頂部我有下面的代碼,在任何我的HTML

<?php include_once 'get_data.php'; ?> 

現在,我可以從index.php內通過在變量名,只需鍵入引用的get_data.php的值,這個工程。

不過,我有一個function()內的index.php我使用檢查值,並返回一個百分比作爲字符串

這個功能看起來是這樣的:

function compareMonths($checkingRevenue) { 
    global $this_month_revenue; 
    global $this_month_sales; 
    global $last_month_revenue; 
    global $last_month_sales; 

    ... 
} 

但是,此功能對於所有四個變量返回「0」。我試圖不把它們設置爲全球一樣。我怎樣才能得到從get_data.php的值在我的函數在index.php的範圍內?

我的解決方案是將函數放在get_data.php中,但我想知道如何正確設置範圍,以便將來可以做這樣的事情。

這混淆我因爲include_once文檔指出

當包括一個文件,它包含代碼繼承就行>其中包括髮生的可變範圍。從調用文件中的該行可用的任何變量將在被調用的文件中可用,從該點開始。但是,包含文件中定義的所有函數和>類都具有全局範圍。

這意味着它應該是可訪問的,不是嗎?

+0

但它們仍然是函數範圍之外的變量,因此您必須將它們傳遞給函數或將它們聲明爲函數內部的全局變量。第一種方法更可取,因爲全局聲明經常在大型應用程序的縮放中丟失。 – 2014-11-04 15:03:40

+0

我討厭wall-of-code .. – Flosculus 2014-11-04 15:04:02

+0

意思是這樣做的正確方法就像'compareMonths($ checkingRevenue,$ this_r,$ this_s,$ last_r,$ last_s){}'? – Hobbyist 2014-11-04 15:04:34

回答

0

假設

global $this_month_revenue; 
global $this_month_sales; 
global $last_month_revenue; 
global $last_month_sales; 

是要傳遞給函數,當你調用它的變量。例如:

compareMonths($checkingRevenue, $this_month_revenue, $this_month_sales); 

function compareMonths($checkingRevenue, $val1, $val2) {}