PHP $GLOBALS


Introduction

$GLOBALS is an associative array of references to all globalle defined variables. Names of variables form keys and their contents are values of associative array.

$GLOBALS example

This example shows $GLOBALS array containing name and contents of global variables

Example

 Live Demo

<?php
$var1="Hello";
$var2=100;
$var3=array(1,2,3);
echo $GLOBALS["var1"] . "
"; echo $GLOBALS["var2"] . "
"; echo implode($GLOBALS["var3"]) . "
"; ?>

Output

This will produce following result. −

Hello
100
123

In following example, $var1 is defined in global namespace as well as a local variable inside function. Global variable is extracted from $GLOBALS array;

Example

 Live Demo

<?php
function myfunction(){
   $var1="Hello PHP";
   echo "var1 in global namespace:" . $GLOBALS['var1']. "
";    echo "var1 as local variable :". $var1; } $var1="Hello World"; myfunction(); ?>

Output

This will produce following result. −

var1 in global namespace:Hello World
var1 as local variable :Hello PHP

Updated on: 18-Sep-2020

493 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements