Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Global Variables

Global variables reside in the global scope, and may be imported in a local scope with the global keyword.

To become a global variable, a variable may use one of the following ways:

  • Be declared as such with the global keyword
  • Be created in the $GLOBALS variable, which is a global variable itself
  • Be created outside any function, method, closure
  • Be a super-global

Global variables provide a way to share data in different and remote scopes. They also provide a way for data to be modified by another part of the code, without warning.

<?php

    global $count;
    $count = 0;
    
    function counter() {
        global $count;
        
        // no return here
        ++$count;
    }
    
    counter(); 
    echo $count; // print 1
    counter(); 
    echo $count; // print 2

?>

Documentation

See Also