PHP variable and its scope

Variable Scopes: The scope of a variable is defined as its extent in the program within which it can be accessed, i.e. the scope of a variable is the portion of the program within which it is visible or can be accessed. Depending on the scopes, PHP has three variable scopes.

Local variables: The variables declared within a function are called local variables to that function and have their scope only in that particular function. In simple words, it cannot be accessed outside that function. Any declaration of a variable outside the function with the same name as that of the one within the function is a completely different variable. For now, consider a function as a block of statements.

Global scope:
<?php
$x = 5; 
function myVar() {
  echo "<p>Variable x inside function is: $x</p>";
}
myVar();
echo "<p>Variable x outside function is: $x</p>";
?>
Local scope:
<?php
function myVar() {
  $x = 5;
  echo "<p>Variable x inside function is: $x</p>";
}
myVar();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
Global scope:
<?php
$x = 5;
$y = 10;
function myVar() {
  global $x, $y, $z;
  $z = $x + $y;
}
myVar();
echo $z; // outputs 15
?>

Leave a Reply