Explain PHP variable scopes (local, global, static).

15 viewsSkills Development

Explain PHP variable scopes (local, global, static).

1. Local Scope

  • A local variable is declared within a routine and it is only accessible within the routine.

  • It does not exist outside the function.

Example:

function greet() {

    $message = “Hello, World!”; // local variable

    echo $message;

}

greet(); // Outputs: Hello, World!

echo $message; // ERROR: Undefined variable

Key point: Local variables are temporary and exist only during the function execution.
2. Global Scope

  • A global variable is defined outside any function, usually at the top of a script.

  • By default, functions cannot access global variables directly.

  • To use them inside a function, you need the global keyword or the $GLOBALS array.

Example using global:

$name = “Abarna”; // global variable

function showName() {

    global $name; // import global variable

    echo $name;

}

showName(); // Outputs: Abarna

Example using $GLOBALS:

$age = 25; // global variable

function showAge() {

    echo $GLOBALS[‘age’]; // access global variable

}

showAge(); // Outputs: 25

Key point:There are global variables which can be accessed within functions, and are given special treatment all over the script.


3. Static Scope

  • A static variable is declared inside a function using the static keyword.

  • Unlike normal local variables, its value persists between function calls.

  • Useful for counters or retaining previous values without using global variables.

Example:

function counter() {

    static $count = 0; // static variable

    $count++;

    echo $count . ” “;

}

counter(); // Outputs: 1

counter(); // Outputs: 2

counter(); // Outputs: 3

Key point: Static variables are local in scope but persistent in value.

Omprakash Gajananan Answered question 11 minutes ago
0

Thanks for sharing this breakdown, it’s a very clear explanation of local, global, and static scope in PHP. Understanding how variables behave in different scopes is essential for writing clean, efficient, and bug-free code.

Omprakash Gajananan Answered question 11 minutes ago
0