← Back to PHP Course | Chapter 5: Functions | Lesson 9 of 10

PHP Scope & Variable Lifetime

Understanding Local Scope

A variable created inside a function exists only within that function's own execution — it's invisible to code outside, and calling the function again starts with a fresh, empty version of that variable rather than remembering anything from the previous call.

Example: Understanding Local Scope

php
<?php
function counter() {
    $count = 0;
    $count++;
    echo $count . "\n";
}
counter();
counter();
?>

Understanding Global Scope

A variable created at the top level of a script, outside any function, is global — but that global scope isn't automatically available *inside* a function. You have to explicitly declare global $variableName; inside the function body before you can read or modify it there.

Example: Understanding Global Scope

php
<?php
$total = 100;

function showTotal() {
    global $total;
    echo $total;
}
showTotal();
?>

The GLOBALS Superglobal Array

PHP mirrors every global variable into a superglobal array called $GLOBALS, accessible from inside any function without needing the global keyword — $GLOBALS[count] reads or writes the same variable that global $count; would give you access to.

Example: The GLOBALS Superglobal Array

php
<?php
$count = 5;

function showCount() {
    echo $GLOBALS['count'];
}
showCount();
?>

Static Variables

Marking a variable static inside a function makes it retain its value between separate calls to that function, instead of resetting to its initial value each time — useful for something like a counter that needs to remember how many times the function has run so far.

Example: Static Variables

php
<?php
function increment() {
    static $count = 0;
    $count++;
    echo $count . "\n";
}
increment();
increment();
increment();
?>

Parameter Variable Scope

A function's own parameters behave exactly like local variables: they receive whatever the caller passed in, exist only for the duration of that single call, and vanish the moment the function finishes and returns.

Example: Parameter Variable Scope

php
<?php
function greet($name) {
    echo "Hello, $name";
}
greet("Alice");
// $name does not exist here, outside the function
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.