Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Variable Scope

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 259
    Comment on it

    PHP Variable Scope

    In PHP there are three variable scope. They are : Local , Global and Static. 

    LOCAL VARIABLE : Local variable is the one which is declared within the function,  has the local scope and can be accessed within the function only.

    <!DOCTYPE html>
    <html>
    <body>
    
    <?php
    function demo() {
         $x = 6; // local scope
         echo "<p>Variable x inside function is: $x</p>";
    } 
    demo();
    
    // using x outside the function will generate an error
    echo "<p>Variable x outside function is: $x</p>";
    ?>
    
    </body>
    </html>

    GLOBAL VARIABLE : Global variable is the one which is declared  outside the function and can be accessed from any function.

    <?php
    $x = 6; // global scope
    
    function demo() {
        // using x inside this function will generate an error
        echo "<p>Variable x inside function is: $x</p>";
    } 
    demo();
    
    echo "<p>Variable x outside function is: $x</p>";
    ?>

    You can use global keyword to access a global variable from within a function.

    <?php
    $x = 15;
    $y = 10;
    
    function demo() {
        global $x, $y;
        $y = $x + $y;
    }
    
    myTest();
    echo $y; // output  25
    ?>

     Use the global keyword before the variables (inside the function) as shown in above example.

    STATIC VARIABLE :  When a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. For this static variable scope is declared.

    <?php
    function demo() {
        static $x = 0;
        echo $x;
        $x++;
    }
    
    demo();
    demo);
    demo();
    ?>

    You can use static keyword to access variable. 

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: