Local Variables in PHP with Example
In PHP, there are three types of variables: local, global, and static variables. In this tutorial, we will understand local variables in PHP and their scope with the help of examples. Later on, we will understand on global and static variables.
The variables which are declared inside a block of a function are called local variables in PHP. The scope of a local variable is limited to that function in which it is defined.
In other words, local variables are only accessible within that function in which they are defined. They are only visible within the block of a function.
Once the execution of the function has finished, the local variable is destroyed, and its value is lost. Therefore, you cannot access it from outside of that function.
Let’s take an example based on the declaration of local variables in PHP.
Example 1:
<?php
// Declare a function.
function display() {
// Declare a local variable.
$msg = "This is a local variable within the function.";
// Display the value of local variable.
echo $msg;
}
// Calling the function.
display();
?>
Output: This is a local variable within the function.
In this example, we have defined a function named display(). Inside the display() function, we have declared a local variable named $msg and assigned a string value to it. After that, we have called the function and displayed the output on the browser. Note that function is a keyword used for defining the function.
Advanced Examples of Local Variables
Let’s take an example in which we will define local variables with the same name in different functions. This is because local variables are only available inside that function in which they are declared.
Example 2:
<?php
// Declaration of functions.
function add() {
// Local variables $x, $y, and $z.
$x = 20;
$y = 30;
$z = $x + $y;
echo $z;
}
function sub(){
$x = 20;
$y = 30;
$z = $x - $y;
echo $z;
}
// Calling the functions.
add();
echo "<br>";
sub();
?>
Output: 50 -30
Example 3:
<?php
// Declaration of functions.
function showMe() {
// Local variable.
$greet = "I am a local variable.";
}
// Calling local variable from outside the function.
echo $greet;
?>
Output: Warning: Undefined variable $greet
As you can see in the above code, we are trying to access a local variable named $greet from outside its scope i.e. outside the function.
Example 4:
<?php
function calculate() {
$result = 10;
$result = 20; // Overwrites the previous value
echo $result;
}
calculate();
?>
Output: 20
In this example, we have reused the variable names within the same scope that can cause confusion and errors. Therefore, you should always try to use unique names for each variable within a function.
If you use the local variable before initializing it, you will get the unpredictable results or warnings.
Example 5:
<?php
function calculate() {
$result;
echo $result;
}
calculate();
?>
Output: Warning: Undefined variable $result