Thursday, 18 February 2016

PHP Variable Scope

Local Variable

     A local variable is accessible only the block where it has defined. When a code block over then the entire local variable inside of block automatically released by the compiler.
<?php
           
            function fun1()
            {                      
                        $a=10;
                        echo $a;
            }
            function fun2()
            {
                        echo $a+10;
                        // Error : Undefined variable: a because it has not defined in fun2 and a is local variable for  fun1
            }          
?>
<?php
            //fun1();
            fun2();
?>

Global Variable

     The scope of a PHP variable depends on where it has defined I.e. when a variable is declared in top side of the PHP code block, then it becomes global variable for all PHP code block but not inside of a function.



<?php
            $a=101;
?>
<?php
            echo $a;
            // Outpur 101
            function test()
            {                      
                        //echo "<br/> Local test " . $a+1;
                        //Error Undefined variable: a
            }
            function testglobal()
            {
                        global $a;
                        echo "<br/> Global Check " . ($a + 1);
            }          
?>
<?php
            //test();
            testglobal();

?>

$GLOBALS instead of global


    The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal
<?php
            $a=110;
?>
<?php
           
            function testglobal()
            {
                       
                        echo "<br/> Accessing global variabal using  $GLOBALS instead of global keyword " . ( $GLOBALS['a'] + 1);
            }          
?>
<?php
           
            testglobal();
?>

Static Variables


Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

<?phpfunction foo(){
static $int = 0; // correct
static $int = 1+2; // wrong (as it is an expression)
static $int = sqrt(121); // wrong (as it is an expression too)

$int++;
echo $int;
}?>

No comments:

Post a Comment