In PHP, the scope of a variable determines its visibility and lifetime within the script. Understanding variable scope is crucial for effective coding and preventing potential issues. This tutorial covers four main types of scope: global, local, static, and class scope.
PHP Scope: Global, Local, Static, and Class Scope
1. Global Scope
A variable declared outside any function or class has a global scope. It can be accessed anywhere in the script, except within functions or classes unless explicitly declared.
1.1 Example of Global Scope
<?php
$globalVar = "I am a global variable";
function showGlobalVar() {
global $globalVar; // Declare the variable as global
echo $globalVar; // Output: I am a global variable
}
showGlobalVar();
?>
In this example, $globalVar
is accessed inside the function by using the global
keyword.
2. Local Scope
A variable declared within a function has a local scope. It is accessible only within that function and cannot be accessed outside of it.
2.1 Example of Local Scope
<?php
function myFunction() {
$localVar = "I am a local variable";
echo $localVar; // Output: I am a local variable
}
myFunction();
// echo $localVar; // This will cause an error: Undefined variable
?>
In this example, $localVar
cannot be accessed outside of myFunction()
, resulting in an error if attempted.
3. Static Scope
A static variable retains its value even after the function has finished executing. This variable is initialized only once and maintains its value across multiple calls to the function.
3.1 Example of Static Scope
<?php
function counter() {
static $count = 0; // Static variable
$count++;
echo $count;
}
counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3
?>
In this example, the static variable $count
retains its value between function calls.
4. Class Scope
Class scope refers to variables defined within a class context, including properties and methods. These variables can be accessed using $this
within class methods.
4.1 Example of Class Scope
<?php
class MyClass {
public $myProperty = "I am a class property";
public function showProperty() {
echo $this->myProperty; // Accessing class property
}
}
$myObj = new MyClass();
$myObj->showProperty(); // Output: I am a class property
?>
In this example, $myProperty
is accessed within the class method showProperty()
using $this
.
5. Conclusion
Understanding variable scope in PHP is essential for writing clean and effective code. By knowing the differences between global, local, static, and class scope, you can better manage variable visibility and lifespan in your applications.