how can i get value from inside of function?

前端 未结 4 1223
感情败类
感情败类 2021-01-23 02:35

Is it possible to get those values inside of function and use those outside of function here is my code:



        
相关标签:
4条回答
  • 2021-01-23 02:43

    Write return $total; inside the function

    0 讨论(0)
  • 2021-01-23 02:44

    You need to "return" the value. See the entry in the PHP manual for this. Basically, return means "exit this function now". Optionally, you can also provide some data that the function can return.

    Just use the return statement:

    <?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 讨论(0)
  • 2021-01-23 02:59

    If you put return $total at the very end of the function (right before the last curly brace), you should be able to use the result.

    0 讨论(0)
  • 2021-01-23 02:59
    1. Your can use global scope. I.e.

      $s = 1;
      function eee()
      {
       global $s;
       $s++;
      }
      echo $s;
      
    2. Your can got var/return var... if your need return more that 1 value - use array

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

    Prefer 2'd. Cause global scope operationing - may cause problems, when app become's large.

    0 讨论(0)
提交回复
热议问题