1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

using variables declared outside of a function

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

  1. pein87

    pein87 New Member

    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