PHP Global variables are the user-defined variables defined on the $GLOBALS superglobal. A superglobal is a special PHP variable that handles tasks like storing cookies, sessions, and server information.
Learn more here.
Variables added to $GLOBALS can be accessed anywhere regardless of scope. Variables defined at the root of a script are attached to $GLOBALS by default. New variables can be attached to $GLOBALS at any point.
The code block below contains a concatNames
function that combines a first and last name. The $first_name and $last_name variables are accessed within the function from $GLOBAL. The new variable, $full_name is attached directly to $GLOBAL.
Line 10 and 11 show that $full_name can be accessed as a normal variable or from the $GLOBALS object.
<?php$first_name = "John";$last_name = "Doe";function concatNames() {$GLOBALS['full_name'] = $GLOBALS['first_name'] . " " . $GLOBALS['last_name'];}concatNames();echo $full_name . "\n";echo $GLOBALS['full_name'];?>