2011-05-21 160 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。導致全球範圍操作 - 可能會導致問題,當應用程序變得很大時。