Avoid Global Variables

ID

php.avoid_global_variables

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Php

Tags

code_smell, global-state

Description

Reports a function or method that reaches into global state, either through a global $x; declaration or through the $GLOBALS superglobal array. Accesses at the script’s top level are ordinary global scope and are not flagged.

Rationale

A function that reads or writes a global variable has a dependency that is invisible in its signature. Its result no longer depends only on its arguments, so it cannot be reasoned about, reused, or unit-tested in isolation, and two callers that both mutate the same global can interfere with each other. Threading the value through parameters and return values makes the dependency explicit and the function self-contained.

<?php
function totalWithTax()
{
    global $cart;                 // FLAW — hidden dependency on a global
    return $cart->total() * 1.21;
}

function totalWithTaxGlobals()
{
    return $GLOBALS['cart']->total() * 1.21; // FLAW — same dependency via $GLOBALS
}

function totalWithTaxClean(Cart $cart): float
{
    return $cart->total() * 1.21; // OK — the dependency is passed in
}

Remediation

Pass the value the function needs as a parameter and return whatever it produces, rather than reading or mutating a global. For shared services prefer dependency injection over the $GLOBALS array.

Framework-mandated globals (WordPress’s $wpdb, $wp_query, $post, …) are exempt: a global declaration is only reported when at least one declared name is outside the configurable allowedGlobals allowlist.