是否可以从函数内部获取值并在函数外部使用这些值?
这是我的代码:
<?php
function cart() {
foreach($_SESSION as $name => $value){
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo $get_row['name'].' x '.$value.' @ £'.number_format($get_row['price'], 2).' = £'.number_format($sub, 2).'<a href="cart.php?remove='.$id.'">[-]</a> <a href="cart.php?add='.$id.'">[+]</a> <a href="cart.php?delete='.$id.'">[Delete]</a><br />';
}
}
$total += $sub ;
}
}
}
?>
现在我的问题是如何获取$total
的值?我想在函数之外使用该值。我有 2 个功能 1 个购物车和 1 个折扣。
我试过return $total;
(在函数内部)
例如
$final = cart () - discount ();
echo $final;
它呼应了两个函数,但是函数内部的代码不做任何数学运算。
最佳答案
您需要“返回”该值。查看entry in the PHP manual for this .基本上,return
的意思是“现在退出这个函数”。或者,您还可以提供函数可以返回的一些数据。
只需使用return
语句:
<?php
function cart()
{
foreach ($_SESSION as $name => $value) {
if ($value > 0) {
if (substr($name, 0, 5) == 'cart_') {
$id = substr($name, 5, (strlen($name) - 5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id=' . mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price'] * $value;
echo $get_row['name'] . ' x ' . $value . ' @ £' . number_format($get_row['price'], 2) . ' = £' . number_format($sub, 2) . '<a href="cart.php?remove=' . $id . '">[-]</a> <a href="cart.php?add=' . $id . '">[+]</a> <a href="cart.php?delete=' . $id . '">[Delete]</a><br />';
}
}
$total += $sub;
}
}
return $total;
}
?>
关于php - 如何从函数内部获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6082160/