Searching...
Thursday 4 October 2012

Local and Global Variables

11:06 pm

Local and Global Variables

Local and Global Variables :

1.      A variable which is specified inside a function is called an local variable and a variable which is specify outside the function is called as global variable.
2.      A local variable is accessable only with in the function where it is declared.
3.      Where as a global variable can be accessed from any where in the program.
4.      The lifetime of local variable is only within the function.
$GLOBALS : is a builtin multidimentional global array of php. That stores get data, post data,cookies,uploader files, error messages happening in a program execution and also excludes the global variables of the application.
The variables present inside $GLOBALS array is known as global variables.
Global : is a keyword of php used for declaring a global variable . a variable declared by using the keyword globsl cannot be intialized.
     <?php
$x=10;
function myfun()
{
    $y=20;
    $GLOBALS['y']=20;
    global $z;
    $z = 30;
      
}
?>
<h1>
<?php
echo $x."--".$y."<br>";
myfun();
print_r($GLOBALS);
echo "<br><br>";
echo $x."--".$y."--".$z;
?>
</h1>
OutPut:
10--
Array ( [GLOBALS] => Array *RECURSION* [_POST] => Array ( ) [_GET] => Array ( ) [_COOKIE] => Array ( ) [_FILES] => Array ( ) [x] => 10 [y] => 20 [z] => 30 )

10--20--30

0 comments:

Post a Comment