За последние 24 часа нас посетили 57977 программистов и 1845 роботов. Сейчас ищут 1109 программистов ...

Как передать переменную из одной функции в другую

Тема в разделе "PHP для новичков", создана пользователем paqwerty, 27 дек 2010.

  1. paqwerty

    paqwerty Активный пользователь

    С нами с:
    2 мар 2007
    Сообщения:
    121
    Симпатии:
    0
    Всем привет!

    Помогите пожалуйста передать переменную из одной функции в другую, уже целую неделю бьюсь и никак...

    Надо передать переменную
    Код (Text):
    1. $pod_zakaz
    из ф.
    Код (Text):
    1. cartGetCartContent()
    в ф.
    Код (Text):
    1. InsertItemIntoCart($itemID)
    вот коды функций:

    Код (Text):
    1.  
    2. function cartGetCartContent()
    3. {
    4.     $cart_content   = array();
    5.     $stock_help     = 0;
    6.     $total_price    = 0;
    7.     $freight_cost   = 0;
    8.     $variants       = '';
    9.    
    10.  
    11.     if (isset($_SESSION["log"]))
    12.     {
    13.         $q = db_query("SELECT itemID, Quantity FROM ".
    14.                 SHOPPING_CARTS_TABLE.
    15.                 " WHERE customerID='".regGetIdByLogin($_SESSION["log"])."'" );
    16.  
    17.         while ($cart_item = db_fetch_row($q))
    18.         {      
    19.             $variants=GetConfigurationByItemId( $cart_item["itemID"] );
    20.  
    21.             $q_shopping_cart_item = db_query("select productID from ".
    22.                     SHOPPING_CART_ITEMS_TABLE." where ".
    23.                     " itemID='".$cart_item["itemID"]."'" );
    24.             $shopping_cart_item = db_fetch_row( $q_shopping_cart_item );
    25.             $q_products = db_query("SELECT name, Price, productID, in_stock, min_order_amount, shipping_freight, free_shipping FROM ".
    26.                     PRODUCTS_TABLE.
    27.                     " WHERE productID='".$shopping_cart_item["productID"]."'");
    28.             if ( $product = db_fetch_row($q_products) )
    29.             {
    30.                 $costUC = GetPriceProductWithOption( $variants,
    31.                             $shopping_cart_item["productID"] );
    32.                 $tmp =
    33.                     array(
    34.                         "productID" =>  $product["productID"],
    35.                         "id"        =>  $cart_item["itemID"],
    36.                         "name"      =>  $product["name"],
    37.                         "in_stock"      =>  $product["in_stock"],
    38.                         "quantity"  =>  $cart_item["Quantity"],
    39.                         "free_shipping" =>  $product["free_shipping"],
    40.                         "costUC"    =>  $costUC,
    41.                         "cost"      =>  show_price($cart_item["Quantity"]*
    42.                                         GetPriceProductWithOption($variants,
    43.                                             $shopping_cart_item["productID"]))   );
    44.  
    45.                 $freight_cost += $cart_item["Quantity"]*$product["shipping_freight"];
    46.  
    47.                 $strOptions=GetStrOptions(
    48.                         GetConfigurationByItemId( $tmp["id"] ));
    49.  
    50.                 if ( trim($strOptions) != "" )
    51.                         $tmp["name"].="  (".$strOptions.")";
    52.  
    53.                 if ( $product["min_order_amount"] > $cart_item["Quantity"] )
    54.                     $tmp["min_order_amount"] = $product["min_order_amount"];
    55.                 if ( $product["in_stock"] <= 0 ) {
    56.                     $stock_help = "1";             
    57.                     }                              
    58.                 if (  $cart_item["Quantity"] > $product["in_stock"] && $product["in_stock"] <= 0 ) {   
    59.                     $product["in_stock"] = 0;                                              
    60.                     $tmp["stock_raznica"] = $cart_item["Quantity"] - $product["in_stock"]; 
    61.                 }                                                  
    62.                 else if (  $cart_item["Quantity"] > $product["in_stock"] && $product["in_stock"] > 0 ) {
    63.                     $tmp["stock_raznica"] = $cart_item["Quantity"] - $product["in_stock"]; 
    64.                 } else {
    65.                     $tmp["stock_raznica"] = 0;
    66.                 }  
    67.                                                         $pod_zakaz = $tmp["stock_raznica"];            
    68.                 $cart_content[] = $tmp;
    69.                 $total_price += $cart_item["Quantity"]*
    70.                         GetPriceProductWithOption($variants,
    71.                             $shopping_cart_item["productID"]);
    72.                
    73.             }
    74.         }
    75.     }
    76.     else
    77.     {
    78.         $total_price    = 0;
    79.         $stock_help         = 0;
    80.         $cart_content   = array();
    81.  
    82.  
    83.         if ( isset($_SESSION["gids"]) )
    84.             for ($j=0; $j<count($_SESSION["gids"]); $j++)
    85.             {
    86.                 if ($_SESSION["gids"][$j])
    87.                 {
    88.                     $session_items[]=
    89.                         CodeItemInClient($_SESSION["configurations"][$j],
    90.                             $_SESSION["gids"][$j]);
    91.  
    92.  
    93.                     $q = db_query("SELECT name, Price, in_stock, shipping_freight, free_shipping FROM ".
    94.                         PRODUCTS_TABLE.
    95.                         " WHERE productID='".$_SESSION["gids"][$j]."'");
    96.                     if ($r = db_fetch_row($q))
    97.                     {
    98.                         $costUC = GetPriceProductWithOption(
    99.                                 $_SESSION["configurations"][$j],
    100.                                 $_SESSION["gids"][$j])
    101.  
    102.                         $id = $_SESSION["gids"][$j];
    103.                         if (count($_SESSION["configurations"][$j]) > 0)
    104.                         {
    105.                             for ($tmp1=0;$tmp1<count($_SESSION["configurations"][$j]);$tmp1++) $id .= "_".$_SESSION["configurations"][$j][$tmp1];
    106.                         }
    107.                         $tmp = array(
    108.                                 "productID" =>  $_SESSION["gids"][$j],
    109.                                 "id"        =>  $id,
    110.                                 "name"      =>  $r[0],
    111.                                 "quantity"  =>  $_SESSION["counts"][$j],
    112.                                 "in_stock"    =>    $r["in_stock"],
    113.                                 "free_shipping" =>  $r["free_shipping"],
    114.                                 "costUC"    =>  $costUC,
    115.                                 "cost"      =>  show_price($costUC * $_SESSION["counts"][$j])
    116.                             );
    117.                         $strOptions=GetStrOptions( $_SESSION["configurations"][$j] );
    118.                        
    119.                         if ( trim($strOptions) != "" )
    120.                             $tmp["name"].="  (".$strOptions.")";
    121.                         if ( $_SESSION["counts"][$j] > $r["in_stock"] ) {  
    122.                         $stock_help = "1";             
    123.                         }                              
    124.                         if ( $_SESSION["counts"][$j] > $r["in_stock"] && $r["in_stock"] <= 0 ) {
    125.                             $r["in_stock"] = 0;            
    126.                             $tmp["stock_raznica"] =  $_SESSION["counts"][$j] - $r["in_stock"]; 
    127.                         }                                                                              
    128.                         else if (   $_SESSION["counts"][$j] > $r["in_stock"] && $r["in_stock"] > 0 ) { 
    129.                             $tmp["stock_raznica"] =  $_SESSION["counts"][$j] - $r["in_stock"];
    130.                         } else {
    131.                             $tmp["stock_raznica"] = 0;
    132.                         }
    133.                                   $pod_zakaz = $tmp["stock_raznica"];
    134.                         $q_product = db_query( "select min_order_amount, shipping_freight from ".PRODUCTS_TABLE.
    135.                                 " where productID=".
    136.                                 $_SESSION["gids"][$j] );
    137.                         $product = db_fetch_row( $q_product );
    138.                         if ( $product["min_order_amount"] > $_SESSION["counts"][$j] )
    139.                             $tmp["min_order_amount"] = $product["min_order_amount"];
    140.  
    141.                         $freight_cost += $_SESSION["counts"][$j]*$product["shipping_freight"];
    142.  
    143.                         $cart_content[] = $tmp;
    144.  
    145.                         $total_price += GetPriceProductWithOption(
    146.                                     $_SESSION["configurations"][$j],
    147.                                     $_SESSION["gids"][$j] )*$_SESSION["counts"][$j];
    148.                     }                      
    149.                 }
    150.             }
    151.     }
    152.     return array(  
    153.             "cart_content"  => $cart_content,
    154.             "total_price"   => $total_price,
    155.             "stock_help"    => $stock_help,
    156.             "freight_cost"  => $freight_cost );
    157.  
    158. }
    код ф. InsertItemIntoCart($itemID):


    Код (Text):
    1.     db_query("insert ".SHOPPING_CARTS_TABLE.
    2.         "(customerID, itemID, pod_zakaz)".
    3.         "values( '".regGetIdByLogin($_SESSION["log"])."', '".$itemID."', '".$pod_zakaz."' )" );
    4.  
    5. }

    ОЧЕНЬ НАДЕЮСЬ НА ВАШУ ПОМОЩЬ!
     
  2. Gromo

    Gromo Активный пользователь

    С нами с:
    24 май 2010
    Сообщения:
    2.786
    Симпатии:
    2
    Адрес:
    Ташкент
    сходу, не смотря код, есть способ - можешь объявить переменную в глобальной области видимости.
    почитай про global $var или суперглобальный массив $GLOBALS['var']
     
  3. paqwerty

    paqwerty Активный пользователь

    С нами с:
    2 мар 2007
    Сообщения:
    121
    Симпатии:
    0
    Gromo спасибо за информацию для изучения.

    На простеньком коде у меня все получается с global, но у меня не получается это применить в коде выше.

    Я заметил такую вещь, что если я объявлю переменную глобальной в коде выше после

    Код (Text):
    1. return array(    
    2.          "cart_content"   => $cart_content,
    3.          "total_price"   => $total_price,
    4.          "stock_help"   => $stock_help,
    5.          "freight_cost"   => $freight_cost );
    , то эта переменная не передается, а если перед , то все гуд.

    Что это значит?
     
  4. Mat

    Mat Активный пользователь

    С нами с:
    12 дек 2006
    Сообщения:
    391
    Симпатии:
    0
    ну почитай тогда ещё про return

    псы:

    А вобще что тут передовать? Зделай одну глобальную переменную и работай с ней хоть во всех функциях., типа:

    Код (Text):
    1. $test=0;
    2.  
    3. function foo1()
    4. {
    5.     global $test;
    6.     return $test++;
    7. }
    8.  
    9.  
    10. function foo2()
    11. {
    12.     global $test;
    13.     return $test++;
    14. }
    15.  
    16. foo1();
    17. foo2();
    18.  
    19. echo $test;
     
  5. paqwerty

    paqwerty Активный пользователь

    С нами с:
    2 мар 2007
    Сообщения:
    121
    Симпатии:
    0
    Т.е., если я вызываю return, то функция прерывается и все что находится ниже return в функции просто бессмысленно. Правильно я понимаю?

    А переменную я могу объявлять в любом месте функции или же нет? Может я что-то не так делаю...

    Вот как я передаю переменную из функции в функцию, но это не работает:

    Код (Text):
    1.  
    2. function cartGetCartContent()
    3. {
    4.    $cart_content    = array();
    5.    $stock_help      = 0;
    6.    $total_price    = 0;
    7.    $freight_cost   = 0;
    8.    $variants       = '';
    9.    
    10.  
    11.    if (isset($_SESSION["log"]))
    12.    {
    13.       $q = db_query("SELECT itemID, Quantity FROM ".
    14.             SHOPPING_CARTS_TABLE.
    15.             " WHERE customerID='".regGetIdByLogin($_SESSION["log"])."'" );
    16.  
    17.       while ($cart_item = db_fetch_row($q))
    18.       {      
    19.          $variants=GetConfigurationByItemId( $cart_item["itemID"] );
    20.  
    21.          $q_shopping_cart_item = db_query("select productID from ".
    22.                SHOPPING_CART_ITEMS_TABLE." where ".
    23.                " itemID='".$cart_item["itemID"]."'" );
    24.          $shopping_cart_item = db_fetch_row( $q_shopping_cart_item );
    25.          $q_products = db_query("SELECT name, Price, productID, in_stock, min_order_amount, shipping_freight, free_shipping FROM ".
    26.                PRODUCTS_TABLE.
    27.                " WHERE productID='".$shopping_cart_item["productID"]."'");
    28.          if ( $product = db_fetch_row($q_products) )
    29.          {
    30.             $costUC = GetPriceProductWithOption( $variants,
    31.                      $shopping_cart_item["productID"] );
    32.             $tmp =
    33.                array(
    34.                   "productID" =>  $product["productID"],
    35.                   "id"      =>   $cart_item["itemID"],
    36.                   "name"      =>   $product["name"],
    37.                   "in_stock"      =>   $product["in_stock"],
    38.                   "quantity"   =>   $cart_item["Quantity"],
    39.                   "free_shipping"   =>   $product["free_shipping"],
    40.                   "costUC"   =>   $costUC,
    41.                   "cost"      =>   show_price($cart_item["Quantity"]*
    42.                               GetPriceProductWithOption($variants,
    43.                                  $shopping_cart_item["productID"]))   );
    44.  
    45.             $freight_cost += $cart_item["Quantity"]*$product["shipping_freight"];
    46.  
    47.             $strOptions=GetStrOptions(
    48.                   GetConfigurationByItemId( $tmp["id"] ));
    49.  
    50.             if ( trim($strOptions) != "" )
    51.                   $tmp["name"].="  (".$strOptions.")";
    52.  
    53.             if ( $product["min_order_amount"] > $cart_item["Quantity"] )
    54.                $tmp["min_order_amount"] = $product["min_order_amount"];
    55.             if ( $product["in_stock"] <= 0 ) {
    56.                $stock_help = "1";            
    57.                }                        
    58.             if (  $cart_item["Quantity"] > $product["in_stock"] && $product["in_stock"] <= 0 ) {    
    59.                $product["in_stock"] = 0;                                    
    60.                $tmp["stock_raznica"] = $cart_item["Quantity"] - $product["in_stock"];    
    61.             }                                        
    62.             else if (  $cart_item["Quantity"] > $product["in_stock"] && $product["in_stock"] > 0 ) {
    63.                $tmp["stock_raznica"] = $cart_item["Quantity"] - $product["in_stock"];    
    64.             } else {
    65.                $tmp["stock_raznica"] = 0;
    66.             }  
    67.            global $x1;
    68.             $x1 = $tmp["stock_raznica"];
    69.             ...
    70.            
    Код (Text):
    1.  
    2. function InsertItemIntoCart($itemID)
    3. {
    4. [b]cartGetCartContent();[/b]
    5.     db_query("insert ".SHOPPING_CARTS_TABLE.
    6.         "(customerID, itemID, pod_zakaz)".
    7.         "values( '".regGetIdByLogin($_SESSION["log"])."', '".$itemID."', '".$x1."' )" );
    8. }
    Может я что-то не так делаю? Помогите плиз...
     
  6. Mat

    Mat Активный пользователь

    С нами с:
    12 дек 2006
    Сообщения:
    391
    Симпатии:
    0
    Конечно не работает - ты вобще смотришь что тебе пишут? Во-первых объяви переменную x1 как глобальную. Во-вторых я не вижу что ты инициализировал её во второй функции:
    Код (Text):
    1. function InsertItemIntoCart($itemID)
    2. {
    3.     global x1;
    4. }
     
  7. paqwerty

    paqwerty Активный пользователь

    С нами с:
    2 мар 2007
    Сообщения:
    121
    Симпатии:
    0
    сори, не заметил...
    Вроде все сделал как надо, но не работает...

    вот код:
    Код (Text):
    1.  
    2. <?php
    3.  
    4. function InsertItemIntoCart($itemID)
    5. {
    6.    global $x1;
    7.    cartGetCartContent();
    8.    db_query("insert ".SHOPPING_CARTS_TABLE.
    9.       "(customerID, itemID, pod_zakaz)".
    10.       "values( '".regGetIdByLogin($_SESSION["log"])."', '".$itemID."', '".$x1."' )" );
    11. }
    12.  
    13. $x1 = 0;
    14.  
    15. function cartGetCartContent()
    16. {
    17.    $cart_content    = array();
    18.    $stock_help      = 0;
    19.    $total_price    = 0;
    20.    $freight_cost   = 0;
    21.    $variants       = '';
    22.    ...
    23.    ...
    24.   global $x1;
    25.   $x1 = 11;
    26.    ...
    27.    ...
    28. }
    29.  
    30. ?>
    Показывает 0
     
  8. asik

    asik Активный пользователь

    С нами с:
    12 июл 2007
    Сообщения:
    211
    Симпатии:
    0
    PHP:
    1. <?php
    2.  
    3. function InsertItemIntoCart($itemID)
    4. {
    5.    $x1=100;
    6. echo $x1;
    7.    $x1 = cartGetCartContent($x1);
    8. echo $x1;
    9.    db_query("insert ".SHOPPING_CARTS_TABLE.
    10.       "(customerID, itemID, pod_zakaz)".
    11.       "values( '".regGetIdByLogin($_SESSION["log"])."', '".$itemID."', '".$x1."' )" );
    12. }
    13.  
    14. $x1 = 0;
    15.  
    16. function cartGetCartContent($x1)
    17. {
    18.    $cart_content    = array();
    19.    $stock_help      = 0;
    20.    $total_price    = 0;
    21.    $freight_cost   = 0;
    22.    $variants       = '';
    23.    ...
    24.    ...
    25. echo $x1;
    26.   $x1 = 11;
    27.    ...
    28.    ...
    29.   return $x1;
    30. }
    31.  
    32. ?>