Variable Scope in PHP
The variable scope in PHP defines the area or region of within the program where a particular variable is visible or accessible.
In other words, a variable scope refers to the part of PHP program within which you can access and manipulate a specific variable. It determines its visibility.
A scope also determines when memory is allocated to a variable and when it is deallocated. This means that the scope not only controls where a variable is visible and accessible but also manages its lifecycle, including the allocation and deallocation of memory associated with the variable.
There are four types of variable scope in PHP programming language. They are:
- Local scope
- Global scope
- Static scope
- Class scope
Local Scope
In PHP, the local scope refers to the area inside a block of a function. When you declare a variable inside the block of a function, it is called local variable. The scope of local variables is limited to the function in which they are defined.
In other words, when you create a local variable inside a function, its scope only remains within the function. It is visible only within the block of that function.
Once the function execution is complete, the local variables are destroyed, and are not available outside that function. Therefore, you cannot access it from outside the block of a function. You cannot also change the value of a local variable from outside of any function block.
Let’s take a very simple example in which we will define a local variable in a function and will try to access from the outside the block of that function.
Example 1:
<?php
// Define a function.
function myFunction() {
$x = 10; // Local scope
echo $x;
}
// Calling the function.
myFunction();
// Accessing the local variable from outside the function.
echo $x;
?>
Output: 10 Error: Undefined variable $x
In this example, we have defined a local variable named $x inside the function. When you try to access it outside the function, PHP throws an error because $x does not exist in the global scope.
Example 2:
<?php
function firstFunction() {
$x = 5; // local scope.
echo $x;
}
function secondFunction() {
$x = 15; // local scope.
echo $x;
}
// Calling functions.
firstFunction();
echo "\n";
secondFunction();
?>
Output: 5 15
In this example, we have defined multiple local variables with the same name in different functions. Each variable is in its own local scope. Therefore, PHP will treat them as separate variables because they exist in different local scopes.
Common Errors
1. Trying to access a local variable outside its function scope results in an undefined variable error.
2. If a local variable defined within a function shares the same name as a global variable, the local variable will take precedence within the function, which might cause unexpected behavior.
Global Scope
In PHP, the global scope refers to the area or region outside of all functions and classes. When you define a variable outside of functions and classes in a PHP program, it is called a global variable.
These variables exist in the global scope. Therefore, variables defined in the global scope are accessible throughout the entire script. You can access them anywhere in the script except within functions or classes. Inside the functions and classes, you can access them using the GLOBAL or global keyword.
Let’s take a very simple example program in which we will define a variable in global scope and access outside of the function.
Example 3:
<?php
// Variable defined in the global scope.
$x = 100;
echo $x;
?>
Output: 100
In this example code, we have defined a variable named $x in the global scope and accessed it outside of any function in the script.
Let’s take an example in which we will access global variables inside the function using the global keyword. Without using it, PHP will not recognize the global variable inside the function.
Example 4:
<?php
$x = 200; // Global scope.
// Define a function.
function myFunction() {
global $x;
echo $x;
}
// Calling function.
myFunction();
?>
Output: 200
In this example, we have defined a variable named $x within the global scope. Inside the function, the statement global $x; tells PHP to use the globally scoped $x instead of creating a local variable.
Example 5:
<?php
$a = 5;
$b = 10;
function sum() {
global $a, $b;
$b = $a + $b;
}
sum();
echo $b;
?>
Output: 15
In this example, both $a and $b are global variables that are accessed and modified inside the sum() function. After calling the function, the value of $b is updated to 15 in the global scope.
Common Errors
1. If you try to access a global variable inside a function without declaring it as global, the PHP interpreter will consider it as undefined.
2. You can easily overwrite the global variables by different parts of the script, which may get unexpected results if not handled carefully.
Static Scope
In PHP, static scope refers to the region within the block of a function where a variable is declared using the static keyword. When you declare variables with the static keyword inside a function, they are called static variables.
These variables retain their values between multiple calls of that function. Static variables are useful for maintaining the track of a value across function calls without using global variables.
Static variables are only visible and accessible within the function in which they are defined, but their values persist across multiple function calls. Let’s take an example based on the static scope in PHP.
Example 6:
<?php
function staticVarScope() {
static $myVar = 30; // local scope.
echo $myVar;
$myVar++;
}
staticVarScope();
echo "\n";
staticVarScope();
?>
Output: 30 31
In this example, we have declared a variable named $myVar using a static keyword. This variable keep its latest or updated value between multiple calls to the staticVarScope() function. Each time staticVarScope() is called, $myVar is incremented, and the updated value is displayed with the help of echo statement.
So, always remember that a variable declared with static keyword inside a function holds its updated or latest value even if the function exits. If you call the function multiple times, it will display the updated value every time.
Class Scope
When you declare a variable in a class, it has a class scope. Variables declared in the class scope are accessible from within any class method using $this keyword. Let’s take an example on it.
Example 7:
<?php
class MyClass {
public $classVariable = 100;
public function myMethod(){
echo $this->classVariable;
}
}
// Creating an instance of the class.
$object = new MyClass();
// Calling the method using reference variable.
$object->myMethod();
?>
Output: 100
In this example code, we have defined a class named MyClass. Inside the class, we have defined a variable named $classVariable and initialized with the value 100. The public keyword indicates that this variable can be accessed from outside the class.
Then, we have declared a myMethod() function inside the class. A method in a class is similar to a function but is specific to the class. The $this keyword is used within a class to refer to the current instance of the class. -> is the object operator used to access variables or methods of the class.
Outside the class, we have created a new instance of the MyClass class and called the myMethod method using the reference variable $object. When myMethod() is called, the echo statement will display the value of $classVariable.
Note that PHP, unlike some other programming languages, does not support block-level scope. Variables declared within if statements, loops, or other block constructs are still accessible outside of those blocks.
Variable Lifetime in PHP
In PHP, the term “variable lifetime” refers to the duration for which a specific variable remains in the computer’s memory. It defines how long the variable exists and can be accessed during the execution of a program.
Once the variable’s lifetime ends, it is removed from memory and no longer accessible. Variables in PHP can have either short or long lifetimes.
(1) Short Lifetime:
A short lifetime typically refers to the duration for which variables exist only during the execution of a specific function or block of code. Variables with short lifetime, such as local variables are created and destroyed within the block of a function. They are automatically destroyed once the execution of the function is completed, and the memory is freed.
(2) Long Lifetime:
Variables with long lifetimes, such as static or global variables, exist for as long as the program is running or until they are explicitly unset. These variables retain their values throughout the execution of the program. They are not automatically destroyed when a function or block of code finishes executing.
Understanding the variable scope and lifetime in PHP programming is important for writing the well-structured and bug-free code. I hope that you will have understood the basic points and practiced all example programs.