PHP

Local and Global variables in PHP

Local variable:

  1. A variable which is specified in a function is known as local  variable.
  2. local variable is accessible only with in the function where it was declared.
  3. the life time of a local variable is with in the function.

Global Variable:

  1. A variable which is specified outside of a function is known as global variable.
  2. Global variable can be accessed anywhere in the program.

$_GLOBALS:

It was an built in multi dimension array in php that stores GETDATA,POSTDATA, cookies, uploader files, error messages occurred in execution and also stores global variables.

The variables present inside $_GLOBAL is called global variables.

Syntax:  $_GLOBALS[‘x’]

global:

Global is keyword of php used for declaring a global variable , a variable declared by using keyword global cant be initialized.

Example:

<?php
$x=10;
function fun()
{
$y=20;
$GLOBALS[‘y’]=20
global $z;
$z=30;
}
echo $x.”—”.$y.”<br>”;
fun();
print_r($GLOBALS);
echo <br>;
echo $x.”—”.$y.”—”.$z;
?>

You Might Also Like