PHP 将变量传递给函数并丢失值

PHP Passing variables to a function and losing values

我正在将一些变量传递给一个函数以进行舍入并添加一个美元符号,但是当这些值进入函数时它们已经丢失了它们的值。

formatDollars($cost, $taxedCost, $shipping, $total)

function formatDollars($cost, $taxedCost, $shipping, $total) {
    $taxedCost = '$'.round($taxedCost, 2);
    $shipping = '$'.round($shipping, 2);
    $total = '$'.round($total, 2);
    $cost = '$'.round($cost, 2);
    return array($cost, $taxedCost, $shipping, $total);
}

list($cost, $taxedCost, $shipping, $total) = formatDollars();

当我输出时,我得到了美元符号,但我所有的数字都变成了零。

你所做的是一种非常迂回的处理方式。您想更改参数的值,因此使它们按引用传递。

formatDollars($cost, $taxedCost, $shipping, $total);
function formatDollars(&$cost, &$taxedCost, &$shipping, &$total)
{
    $taxedCost = '$'.round($taxedCost, 2);
    $shipping = '$'.round($shipping, 2);
    $total = '$'.round($total, 2);
    $cost = '$'.round($cost, 2);
}

现在,变量被传入,函数内对它们所做的任何更改实际上都会改变它们。您不需要 return 任何东西。

顺便说一句 - 你的函数失败了,因为第二次调用(使用 list 命令)没有将任何参数传递给函数。

此外 - 我会阅读 number_format。如果你四舍五入 (3,2),你得到 3,而不是 3.00。

当后面跟着 $ 符号时,它可能被视为变量... 您可以按照以下代码

formatDollars($cost, $taxedCost, $shipping, $total)

 function formatDollars($cost, $taxedCost, $shipping, $total) {
 setlocale(LC_MONETARY, 'en_US');
 $taxedCost = round($taxedCost, 2);
 $taxedCost =money_format('%i', $taxedCost) 
 return array( $taxedCost);
  }

我最终找到了自己问题的答案

在我将变量发送到函数的行中,它不喜欢没有变量等于,所以当我最后说我的变量等于发送到函数时。

function formatDollars($numberFormatted)
    {
        $numberFormat = '$'.round($numberFormatted, 2);
        return $numberFormat;
    }
    $cost = formatDollars($cost);
    $taxedCost = formatDollars($taxedCost);
    $shipping = formatDollars($shipping);
    $total = formatDollars($total);