1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

using variables declared outside of a function

Discussion in 'PHP' started by pein87, Dec 29, 2010.

  1. pein87

    pein87 New Member

    Joined:
    Aug 6, 2010
    Messages:
    173
    Likes Received:
    47
    Trophy Points:
    0
    Occupation:
    Web Dev
    Location:
    Limbo
    Well I'm sure someone here has wondered why wont my function use the variable I defined outside of it like it does in javascript? Php does not have global variables by default so if you define a variable in a function it is closed for use in that function naturally but if you define a variable you can use it in a function by setting it as global.

    PHP:
    <?php

    $myName 
    "pein87";

    function 
    sayMyName()
    {

        echo 
    $myName;

    }

    sayMyName();

    ?>
    The above will give an error call to undefined variable myName.

    To get around this we can use global declaration in the function.

    GLOBAL
    This makes the variable global so it will use the value from a variable not defined in the function. This makes the variables scope global.

    PHP:
    <?php

    $myName 
    "pein87";

    function 
    sayMyName()
    {

       global 
    $myName;

        echo 
    $myName;

    }

    sayMyName();

    ?>
    The above would print "pein87" on the screen because its now using the global variable $myName.
     
    Last edited: Dec 29, 2010

Share This Page