PHP Keywords: global

17 February 2019 - 7:41am

Welcome to my series on every PHP keyword and its usage. Today's item: global.

The global keyword allows you to get and set a variable from the global scope. This means that a variable can be defined and referenced from anywhere within your codebase.

Using global is heavily contraindicated. Globals tightly couple various unrelated sections of your code together, and make it so that it's difficult to reason about where a variable has been defined, or when it was updated.

Note: If you must use a global variable, consider using the $GLOBALS array. This is a superglobal, available from anywhere, and it makes it clear that you're using or updating a global variable.

Usage

<?php
$counter = 0;

function incrementCounter()
{
    global $counter;

    $counter += 1;
    echo $counter;
}

incrementCounter();