【发布时间】:2013-11-10 11:02:58
【问题描述】:
尝试了解如何在 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>
完全符合我的要求! 谢谢您的帮助!我知道数组可以帮助解决这个问题,但我现在才刚刚在我的课程中谈到这一点。
【问题讨论】:
-
对您的函数的调用的每次迭代一次只能处理一个产品,因此您的总计将永远是单个产品的价值,因此即使您的输入中有 30 个产品,它也会只在你能做的就是传递一个输入数组通过它时才运行它,我会用更多细节给出一个完整的答案。
-
我建议你去学习PHP中的OOP编程。这样,你会比现在舒服得多。特别是对于您的产品篮子。
-
听起来不错,感谢您的建议! Nettuts+有课程,我正在考虑参加。
标签: php function variables if-statement assignment-operator