Sling Academy
Home/PHP/Variable Scope in PHP: Local, Global, Static

Variable Scope in PHP: Local, Global, Static

Last updated: January 09, 2024

Introduction

Grasping the concept of variable scope is essential for writing robust PHP programs. We’ll explore the nuances of local, global, and static scope to give you a mastery over how variables behave in different contexts.

The Basics of Variable Scope

In PHP, the scope of a variable determines its accessibility within different parts of a script. Someone has aptly said that a variable’s scope can be imagined as the room in which it lives; some variables live in small, private rooms (local scope), while others tend to roam through the entire house (global scope).

<?php
function testFunction() {
    $localVar = 'I am local.';
    echo $localVar;
}

testFunction();
//echo $localVar; // This will cause an error
?>

The above code illustrates a local variable’s scope: access is limited to within the function it is defined. Attempting to echo it outside its ‘room’ results in an error.

Global Scope and the global Keyword

Variables defined outside of any function have a global scope and can be accessed from anywhere after their definition. However, to access them within functions, you must declare them as global using the global keyword.

<?php
$globalVar = 'I am global.';

function showGlobal() {
    global $globalVar;
    echo $globalVar;
}

showGlobal();
?>

Precision with the global keyword avoids unwanted side effects and ensures organized communication between different parts of the script.

The $GLOBALS Array

The $GLOBALS array is a built-in associative array containing references to all variables with global scope. This array provides an alternative method to access global variables, which may be more direct than the global keyword in certain scenarios.

<?php
$GLOBALS['globalVar'] = 'Access me anywhere!';

function showGlobal() {
    echo $GLOBALS['globalVar'];
}

showGlobal();
?>

This method can come in handy when dealing with numerous variables or when clarity of reference is paramount. Remember, with great power comes great responsibility.

Static Variables

Variables within a function can be made static by using the static keyword. This preservation of state between function calls allows a function to remember the value of a variable from its last call.

<?php
function countVisits() {
    static $count = 0;
    $count++;
    echo $count;
}

countVisits();
// The variable $count will now retain its value even when the function execution is completed
?>

The example above demonstrates how static variables maintain their scope ‘privately’ yet remember their data across function invocations. They are vital for tasks requiring persistence without polluting the global space.

Advanced Scope – Closure and Variable Inheritance

PHP Closures are anonymous functions that can inherit variables from the parent scope using the use keyword. This feature provides a method to pass state into an anonymous function without using global variables.

<?php
$greeting = 'Hello';
$whom = 'World';

$helloWorld = function() use ($greeting, $whom) {
    echo $greeting . ' ' . $whom;
};

$helloWorld();
?>

The example beautifully illustrates how the use keyword can subtly pass down a variable’s value, offering a measure of control that would impress even the most meticulous programmer.

Conclusion

Understanding variable scope in PHP is foundational to writing elegant and effective code. Whether confined to local quarters, enjoying the expanses of global territory, or maintaining persistent traits with ‘static’ poise, variable handling in PHP is a craft in itself. Embrace these concepts, and you will navigate the variable landscape with the grace of an experienced developer.

Next Article: Variable References in PHP: Explanation with Examples

Previous Article: PHP keywords and reserved words you should know

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array