Scope of PHP Variables

The scope of PHP variables are the ranges or part of the code where they are declared and used. There are total three types of the scope of PHP variables which are:

Local Scope in PHP

A local Scope in PHP is that a variable is only declared and accessed within a function. If you declared it within the function and tried to access it outside the function then its not possible. Because outside the function is not the scope of that variable.

<!DOCTYPE html>
<html>
<body>

<?php
function myname() {
  $name = "Sara";
  echo "So, the name inside the function is: $name";
  echo "<br>";
} 
myname();
echo "But the name outside the function is: $name";
?>

</body>
</html>

Now, in above example, when you call the variable $name in the function, then it displays the exact value. But when you call it outside the function then it displays an error.

Global Scope in PHP

On the other side, a global scope in PHP is that when a variable is declared outside the function and can also accessed outside only. There is another solution to call a variable within a function when you declared it outside the function with global keyword.

<!DOCTYPE html>
<html>
<body>

<?php
$car = "Toyota";
 
function mycar() {
  echo "The value of car inside the function is: $car";
  echo "<br>";
} 
mycar();

echo "The value of car outside the function is: $car";
?>

</body>
</html>

Same as above, in this case you declared a variable of $car outside the function and call it outside. So, it gives you correct value. But in other case, when you will try to call it inside the function, it will give you an error.

Static Scope in PHP

Normally, when we write a program, we declared a variable and when a function is executed then all the variables inside it will destroy automatically. But in some cases, we don’t want to destroy some variables and for that we can use a static variable in PHP. Use static keyword for this purpose.

<!DOCTYPE html>
<html>
<body>

<?php
function myvariable() {
  static $a = 0;
  echo $a;
  $a++;
}

myvariable();
echo "<br>";
myvariable();
?> 

</body>
</html>