Home » PHP

PHP $GLOBALS (Super Global) Variable with Example

PHP $GLOBALS: Here, we are going to learn about a super global variable named $GLOBALS in PHP with example.
Submitted by Kongnyu Carine, on May 25, 2019


PHP $GLOBALS is the only superglobal that does not begin with an underscore (_). It is an array that stores all the global scope variables.

$GLOBALS in PHP is used to access all global variables (variables from global scope) i.e. the variable that can be accessed from any scope in a PHP script.

Example of $GLOBALS in PHP

We will see how to access a variable defined globally with the $GLOBALS superglobal?

PHP code to demonstrate example of $GLOBALS

	//global variable
	$name = 'my name is sam';
	function sayName() {
		echo $GLOBALS['name'];
	//calling the function


my name is sam

By defining the $name variable it automatically is stored in the superglobal variable $GLOBALS array. This explains why we can access it in the sayName() function without defining it in the function.

PHP code to find sum of two numbers by accessing global variables using $GLOBALS

	//global variables
	$num1 = 36;
	$num2 = 24;
	//function to access global variables
	function add2Numbers() {
		$GLOBALS['sum'] = $GLOBALS['num1'] + $GLOBALS['num2'];
	//calling function
	//printing sum using global variable
	echo $sum;



In the code above, num1 and num2 are global variables so we are accessing them using $GLOBALS, and sum is a variable present within $GLOBALS, thus, it is accessible from outside the function also.



Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.