PHP Variables Scope
Variable scope in PHP refers to the context in which a variable is defined and accessible. Understanding variable scope is essential for managing variable visibility and avoiding conflicts in your code.
Key Topics
Local Scope
Variables declared within a function are local to that function and cannot be accessed outside of it.
<?php
function localScopeExample() {
$localVar = "I am local";
echo $localVar; // Outputs: I am local
}
localScopeExample();
// echo $localVar; // This will cause an error as $localVar is not accessible here
?>
Global Scope
Variables declared outside of any function have a global scope and can be accessed from anywhere in the script. To access a global variable within a function, the global
keyword must be used.
<?php
$globalVar = "I am global";
function globalScopeExample() {
global $globalVar;
echo $globalVar; // Outputs: I am global
}
globalScopeExample();
echo $globalVar; // Outputs: I am global
?>
Static Scope
Static variables are declared within a function and retain their value across multiple calls to that function. They are not destroyed when the function execution ends.
<?php
function staticScopeExample() {
static $count = 0;
$count++;
echo $count . "\n"; // Outputs the incremented count each time the function is called
}
staticScopeExample(); // Outputs: 1
staticScopeExample(); // Outputs: 2
staticScopeExample(); // Outputs: 3
?>
Summary of Variable Scopes
- Local Scope: Variables defined within a function; not accessible outside.
- Global Scope: Variables defined outside functions; accessible globally.
- Static Scope: Variables that maintain their value between function calls.