2014-11-04 79 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) {}