Scope of variable | PHP


There are three types of scope of variable :
  1. Local variable
  2. Global variable 
  3. Static variable 
1. Local variable:  
-Local variable declared inside the function called as local variable and scope only that of function
-Local variable cannot be accessed outside the function
-Local variable can be used outside the function using function name as shown in below example

Example:

<!DOCTYPE html>
<html>
<head>
 <title>Shivam's web</title>
</head>
<body>
<?php
$a=2;
function dis()
{
 $a=1;//loacl
 echo "loacl a=",$a;
 global $a;
 echo "<br/>gloabl a=",$a;
 echo "<br/>";
}
echo dis().$a
?>

</body>
</html>


2. Global variable:
-Global variable declares outside the function
-When we want to use inside the function use global keyword before the variable as shown

Example:

<!DOCTYPE html>
<html>
<head>
 <title>Shivam's web</title>
</head>
<body>
<?php
$a=2;
function dis()
{
 $a=1;//loacl
 echo "loacl a=",$a;
 global $a;
 echo "<br/>gloabl a=",$a;
 echo "<br/>";
}
echo dis().$a
?>

</body>
</html>


3. Static variable:
-Static variable declare within a function 
-Static variable reset every time when it calls in PHP

Example:

<!DOCTYPE html>
<html>
<head>
 <title>cwipedia.in</title>
</head>
<body>
<?php
function dis()
{
 static $a=0;
 $a++;
 return $a;
}
echo dis(),"<br/>";
echo dis(),"<br/>";
echo dis(),"<br/>";


 ?>
</body>
</html>


Solved Queries:-

  • Scope of variables in PHP
  • Example of Local variable in PHP
  • Example of global variable in PHP
  • Example of static variable in PHP
  • How to access local variable outside the function in PHP

Comments