2011-05-21 163 views
1

是否有可能得到这些值的函数中,并使用功能 这里外面那些是我的代码:如何从函数内部获取值?

<?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.' @ &pound;'.number_format($get_row['price'], 2).' = &pound;'.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折扣 我试过return $ total; (的函数内部) 例如

$final = cart() - discount(); 
echo $final; 

其回波出buth功能回波码的功能在'r不做任何工科数学操作。

+0

return statement .....? – Pushpendra 2011-05-21 13:55:42

+0

所以你在'cart()'函数中尝试'返回$ total;'? – 2011-05-21 13:55:51

+0

你不应该在那样的函数里做echo。因为,如果我想运行你的功能,我突然从你的回声中得到意想不到的输出。一个函数应该完成一项工作,返回一个值,然后完成。 – 2011-05-21 14:19:26

回答

3

您需要“返回”该值。请参阅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 . ' @ &pound;' . number_format($get_row['price'], 2) . ' = &pound;' . 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; 
    } 
?> 
+0

嘿,我做到了,但是它也显示了我的功能中间的回显代码,看看我的问题。并告诉我抓住唯一的总价值的方式 – hamp 2011-05-21 14:29:43

0

如果你把return $total在函数(最后一个大括号前右)的尽头里面,你应该能够使用结果。

0
  1. 您可以使用全局范围。即

    $s = 1; 
    function eee() 
    { 
    global $s; 
    $s++; 
    } 
    echo $s; 
    
  2. 你能搞到VAR /回报VAR ...如果你需要返回更多的值1 - 使用数组

    function eee($s) 
    { 
        return $s++; 
    } 
    eee($s=1); 
    echo $s; 
    

不想2'd。导致全球范围操作 - 可能会导致问题,当应用程序变得很大时。