Sharing variables between functions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sharmilah
    New Member
    • Jun 2007
    • 20

    Sharing variables between functions

    Hi all

    It's me again.. I have a variable to which i am assigning a value in one function. I have to use the variable with the same value assigned in another function. How can I do this. I've tried to portray this in the following codes

    Thanks.


    [PHP]Function x
    {
    $a =25
    }

    Function y
    {
    If ($a=25)
    sql_insert();
    }[/PHP]
  • ak1dnar
    Recognized Expert Top Contributor
    • Jan 2007
    • 1584

    #2
    Originally posted by sharmilah
    Hi all

    It's me again.. I have a variable to which i am assigning a value in one function. I have to use the variable with the same value assigned in another function. How can I do this. I've tried to portray this in the following codes

    Thanks.


    [PHP]Function x
    {
    $a =25
    }

    Function y
    {
    If ($a=25)
    sql_insert();
    }[/PHP]
    [CODE=php]
    <?php
    function FuncOne(){
    $toFuncTwo = 25; // CHANGE THIS
    return $toFuncTwo;
    }

    function FuncTwo($Return edValuefromFunc One){
    if($ReturnedVal uefromFuncOne== 25)
    {
    $Msg = 'True';
    }else
    {
    $Msg = 'False';
    }
    return $Msg;
    }
    $returnValue =FuncOne();
    print FuncTwo($return Value);
    ?>
    [/CODE]

    Comment

    • ronnil
      Recognized Expert New Member
      • Jun 2007
      • 134

      #3
      you could also make a "global" variable

      [PHP] $var = '';

      function funcOne()
      {
      $var = 25;
      }

      function funcTwo()
      {
      echo $var;
      }

      echo $var; //outputs an empty string
      funcOne();
      funcTwo(); //outputs 25
      [/PHP]
      but i like ajaxrands solution more, since one rarely want to use global variables unless unavoidable :)

      Comment

      • pbmods
        Recognized Expert Expert
        • Apr 2007
        • 5821

        #4
        Changed thread title to better describe the problem.

        Comment

        Working...