About Lesson
Variable scope (global, local, static)
In PHP, the scope of a variable determines where you can access or use that variable in your program. There are mainly 3 types of variable scope in PHP:
- Local Scope
- Global Scope
- Static Scope
1. Local Scope:
- A variable declared inside a function is local to that function.
- You cannot access it outside the function.
Example:
PHP
<?php
function testLocal() {
$x = 10; // Local variable
echo "Inside function: x = $x <br>";
}
testLocal();
echo "Outside function: x = $x"; // Error: x not defined outside
?>
Explanation:
$x
only exists inside the function.- Output:
- Inside function: x = 10
- Outside function: x =
2. Global Scope:
- A variable declared outside a function has global scope.
- To access it inside a function, you must use the global keyword.
Example:
PHP
<?php
$x = 20; // Global variable
function testGlobal() {
global $x; // Import global variable into function
echo "Inside function: x = $x <br>";
}
testGlobal();
echo "Outside function: x = $x <br>";
?>
Explanation:
- Without the
global
keyword,$x
inside the function would not work. - Output:
- Inside function: x = 20
- Outside function: x = 20
Another Way:
- PHP offers a unique superglobal array named $GLOBALS[] that allows access to global variables within functions.
Example:
PHP
<?php
$a = 5;
$b = 10;
function sum() {
$GLOBALS['c'] = $GLOBALS['a'] + $GLOBALS['b'];
}
sum();
echo "The sum is: " . $c;
?>
Explanation:
- Output: The sum is: 15
3. Static Scope:
- Normally, when a function ends, local variables are destroyed.
- If you declare a variable as static, it will keep its value between function calls.
Example:
PHP
<?php
function counter() {
static $count = 0; // Static variable
$count++;
echo "Count = $count <br>";
}
counter();
counter();
counter();
?>
Explanation:
- Output:
- Count = 1
- Count = 2
- Count = 3