【问题标题】:Confusion with PHP scope while using functions使用函数时与 PHP 范围混淆
【发布时间】:2014-11-04 14:59:57
【问题描述】:

我有两个不同的 .php 文件,第一个名为 get_data.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 的值,这样就可以了。

但是,我在 index.php 内有一个 function(),用于检查值并以字符串形式返回百分比

这个函数看起来像这样:

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 的文档说明了

当一个文件被包含时,它包含的代码继承了包含发生的行的变量范围。从那时起,调用文件中该行的任何可用变量都将在被调用文件中可用。但是,包含文件中定义的所有函数和 > 类都具有全局范围。

这意味着它应该是可访问的,不是吗?

【问题讨论】:

  • 但它们仍然是函数范围之外的变量,因此您必须将它们传递给函数或将它们声明为函数内部的全局变量。第一种方法更可取,因为全局声明经常在大型应用程序的扩展中丢失。
  • 我讨厌代码墙..
  • 意思是正确的做法是像compareMonths($checkingRevenue, $this_r, $this_s, $last_r, $last_s) { } ?
  • 他可能知道问题所在,但如果他没有想到将变量作为参数传递,他可能无法分辨什么是相关的,什么不是。

标签: php scope


【解决方案1】:

假设

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) {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2017-07-15
    • 2020-02-16
    • 2014-04-14
    相关资源
    最近更新 更多