Variables Scope in PHP - Availability of Variables in PHP program - PHP Variables Scope


Variables Scope in PHP - Availability of Variables in PHP program - PHP Variables Scope 

There are 3 types of Variables Scope available in PHP. The Scope concern the variables availability for their use in our program-


  • local
  • global
  • static
Local Scope :- To know about local scope of a variable you need to see an example so i am showing a good example to you.

<?php
$x;  //global scope

function show()
{
$str="Hello PHP"; //local scope can't be access outside the function
echo $str;
}

?>

Global Scope:- To know about global scope of a variable you need to see an example so i am showing a good example to you.

<?php
$x="Hello Global";  //global scope

function show()
{
$str="Hello PHP"; //local scope can't be access outside the function
echo $str;
echo global $x;    //global keyword is used to access global variables
}

?>

Static Scope:- When a function work is completed normally its variables values are deleted but if you want the function's variables should not delete and remain its previous values then we use the "static" keyword before declaring it.
Example:-

<?php
$x="Hello Global";  //global scope

function show()
{
$str="Hello PHP"; //local scope can't be access outside the function
static $x=0;
$x++;
}
show();
show();
show();
?>

According to the above example the show() function's variable x's last value is 3 because it is static variable.

{ 0 comments... read them below or add one }

Post a Comment