尝试学习如何在 PHP 中使用函数:如果我想以 0 值开始一个变量,并使用赋值运算符添加到它,我将如何在函数中执行此操作?很难用语言来形容,所以举个例子:
<?php
function tally($product){
// I want these to be the starting values of these variables (except for $tax, which will remain constant)
$tax = 0.08;
$total_price = 0;
$total_tax = 0;
$total_shipping = 0;
$grand_total = 0;
// So, the program runs through the function:
if($product == 'Candle Holder'){
$price = 11.95;
$shipping = 0;
$total_price += $price;
$total_tax += $tax * $price;
$total_shipping += $shipping * $price;
$grand_total = ($total_price + $total_tax + $total_shipping);
}
else if($product == 'Coffee Table'){
$price = 99.50;
$shipping = 0.10;
$total_price += $price;
$total_tax += $tax * $price;
$total_shipping += $shipping * $price;
$grand_total = ($total_price + $total_tax + $total_shipping);
}
else if($product == 'Floor Lamp'){
$price = 44.99;
$shipping = 0.10;
$total_price += $price;
$total_tax += $tax * $price;
$total_shipping += $shipping * $price;
$grand_total = ($total_price + $total_tax + $total_shipping);
}else{
echo '<li>Missing a product!</li>';
}
// And then, it echoes out each product and price:
echo '<li>'.$product.': $'.$price;
// To test it, I echo out the $grand_total to see if it's working:
echo '<br>---'.$grand_total;
} //end of function tally()
// End of the function, but every time I call
tally('Candle Holder');
tally('Coffee Table');
tally('Floor Lamp');
?>
它不会添加到所有三种产品的 $grand_total 中。我知道这是因为函数从开头(顶部)运行并将 $grand_total 重置为 0。如果我尝试将原始值变量放在函数之外,浏览器会返回错误:未定义变量。
我知道这很混乱,所以请告诉我是否需要提供更多信息。谢谢!
编辑
找到了另一种简化它的方法。完全忘记了这个return
功能:
<B>Checkout</B><br>
Below is a summary of the products you wish to purchase, along with totals:
<?php
function tally($product, $price, $shipping){
$tax = 0.08;
$total_tax = $tax * $price;
$total_shipping = $shipping * $price;
$grand_total = ($total_price + $total_tax + $total_shipping);
echo '<li>'.$product.': $'.$grand_total;
return $grand_total;
} //end of function tally()
?>
<ul>
<?php
$after_tally = tally('Candle Holder', 11.95, 0);
$after_tally += tally('Coffee Table', 99.50, 0.10);
$after_tally += tally('Floor Lamp', 49.99, 0.10);
?>
</ul>
<hr>
<br>
<B>Total (including tax and shipping): $<? echo number_format($after_tally, 2); ?></B>
正是我想要的!谢谢您的帮助!我知道数组可以帮助解决这个问题,但我现在才在我的课程中谈到这一点。