SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Jul 2000
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    G'day, everybody...

    My code messed up as the variables set within a function cannot be accessed outside it. How to make the variable set inside a function accessible outside the function??

    - Jeremy


  2. #2
    SitePoint Enthusiast
    Join Date
    Jul 1999
    Posts
    62
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There are 2 ways:

    1. return the variable (you can also return an array of vars):
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">code/font><HR><pre>function test(){
    $varname=1;
    return varname;
    }[/code]


    2. Make the var global
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">code/font><HR><pre>
    $varname=1;
    function test(){
    global $varname;
    $varname=2;
    }[/code]

    Misja



    [This message has been edited by Misja (edited July 28, 2000).]

  3. #3
    SitePoint Member
    Join Date
    Jul 2000
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Declare the variables global inside the function. For example:

    <BLOCKQUOTE><font size="1" face="Verdana, Arial">code/font><HR><pre>function test ()
    {
    global $test_value, $test_value2;
    $test_value = "testing";
    $test_value2 = " scope";
    }

    function test2 ()
    {
    // declare the variables global
    global $test_value, $test_value2;
    // prints "testing scope" if the variables have been set
    echo $test_value . $test_value2;
    }

    // doesn't print anything
    echo $test_value . $test_value2;

    // doesn't print anything
    test2 ();

    // call the test() function
    test();

    // this will print: testing scope
    echo $test_value . $test_value2;

    // this will print: testing scope
    test2 ();[/code]


    ------------------
    Antti
    Huotari.com/antti/
    LinuxWebDevNews.com

  4. #4
    SitePoint Wizard silver trophy Karl's Avatar
    Join Date
    Jul 1999
    Location
    Derbyshire, UK
    Posts
    4,411
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There are other ways as well you can pass the variable into the function by reference:
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">code/font><HR><pre>
    function ( &$myvar1, &$myvar2 ) {

    $myvar1 = 1;
    $myvar2 = 2;

    }
    [/code]

    ------------------
    Karl Austin
    KDA Web Services
    "Everyone has a photographic memory. Some just don't have film."


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •