PHP Variable Scopes - Local, Global, and Static - Codingque

PHP Variable Scopes: Local, Global, and Static

Explore local, global, and static variable scopes in PHP with practical examples and explanations.

1. Local Variables

Local variables are declared inside a function or block and can only be accessed within that function or block.

<?php
function localScope() {
    $localVar = "I am local";
    echo $localVar; // Outputs: I am local
}

localScope();
// echo $localVar; // Error: Undefined variable
?>

Explanation: The variable $localVar is defined inside the localScope() function and is accessible only within that function. Trying to access it outside the function will result in an error.

2. Global Variables

Global variables are declared outside of functions and are accessible from anywhere in the script. However, they need to be explicitly declared as global inside functions to be accessed.

<?php
$globalVar = "I am global";

function accessGlobal() {
    global $globalVar;
    echo $globalVar; // Outputs: I am global
}

accessGlobal();
echo $globalVar; // Outputs: I am global
?>

Explanation: The variable $globalVar is defined outside of the accessGlobal() function. To use it inside the function, you must declare it as global. It is accessible both inside and outside the function.

3. Static Variables

Static variables are declared within a function and retain their value between function calls. They are useful for preserving state information across multiple invocations.

<?php
function staticScope() {
    static $count = 0;
    $count++;
    echo $count . "<br>";
}

staticScope(); // Outputs: 1
staticScope(); // Outputs: 2
staticScope(); // Outputs: 3
?>

Explanation: The variable $count is declared as static. It retains its value between calls to staticScope(), which allows it to increment on each call.

Previous Next
Modern Footer