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

时间:2015-03-26 13:54:56

标签: php function null

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

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();

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

3 个答案:

答案 0 :(得分:1)

你正在做的是一种非常全面的处理方式。您想要更改参数的值,因此请将它们传递给引用。

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

现在,传入变量,并且在函数内对它们所做的任何更改实际上都会更改它们。你不需要退货。

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

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

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