是否可以在PHP中使用全局变量而不必通过引用传递?

问题描述 投票:0回答:1

我有以下适用的PHP代码:

$totalRent = 0;
$totalLate = 0;
$totalOther = 0;
$totalService = 0;

function rentsBreakdown($array, &$totalRent, &$totalLate, &$totalOther, &$totalService){
    if (is_array($array)){
        foreach ($array as $row){
            if ($row['Type'] == "Rent")
                $totalRent += $row['Amount'];
            if ($row['Type'] == "Late Fee")
                $totalLate += $row['Amount'];
            if ($row['Type'] == "Other Fee")
                $totalOther += $row['Amount'];
            if ($row['Type'] == "Service Fee")
                $totalService += $row['Amount'];
        }
    };
};

rentsBreakdown($form_data['list'][37], $totalRent, $totalLate, $totalOther, $totalAttorney); //works
echo money_format('%.2n', ($totalRent));

但是,您会发现必须传递的更多可能变量变得难以理解。每次调用该函数时,都必须将所有其他var放入其中。

我希望像下面这样使版本更易于使用:

$totalRent = 0;
$totalLate = 0;
$totalOther = 0;
$totalService = 0;

function rentsBreakdownNew($array){
    global $totalRent, $totalLate, $totalOther, $totalService;
    if (is_array($array)){
        foreach ($array as $row){
            if ($row['Type'] == "Rent")
                $totalRent += $row['Amount'];
            if ($row['Type'] == "Late Fee")
                $totalLate += $row['Amount'];
            if ($row['Type'] == "Other Fee")
                $totalOther += $row['Amount'];
            if ($row['Type'] == "Service Fee")
                $totalService += $row['Amount'];
        }
    };
};

rentsBreakdownNew($form_data['list'][37]); //doesn't work
echo money_format('%.2n', ($totalRent));

在此示例中,我可以仅在数组上调用该函数,而不必包含所有可能性,如果添加更多可能性,则可以更新该函数中的全局变量,而不必在任何地方编辑该函数调用。另外,在您的函数中将var设置为global的目的不应该与通过函数传递一样吗?

编辑:传入的数组看起来像:

Array (
  [0] => Array ( 
    [Amount] => 1500
    [Type] => Rent
    [Start Date] => 10/15/2019 
    [End Date] => 10/15/2019
  )
)
php pass-by-reference
1个回答
0
投票

$_GLOBALS超级变量在所有作用域中都存在。

$ GLOBALS-引用全局范围内的所有可用变量

$_GLOBALS

上面的示例将输出类似于:

<?php
function test() {
    $foo = "local variable";

    echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
    echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Example content";
test();
?>
© www.soinside.com 2019 - 2024. All rights reserved.