PHP $GLOBALS (Super Global) Variable with Example

PHP $GLOBALS: Here, we will find out about an overly worldwide variable named $GLOBALS in PHP with example.

PHP $GLOBALS

PHP $GLOBALS is the main superglobal that doesn’t start with an underscore (_). It is a cluster that stores all the worldwide extension variables.

$GLOBALS in PHP is utilized to get to every worldwide variable (variables from the worldwide extension) for example the variable that can be gotten to from any extension in a PHP content.

Example of $GLOBALS in PHP

We will perceive how to get to a variable characterized all-inclusive with the $GLOBALS superglobal?

PHP code to exhibit an example of $GLOBALS

<?php
	//global variable
	$name = 'my name is pam';
	
	//function
	function sayName() {
		echo $GLOBALS['name'];
	}
	
	//calling the function
	sayName();
?>

Output:

my name is pam

By characterizing the $name variable it consequently is put away in the superglobal variable $GLOBALS exhibit. This clarifies why we can get to it in the sayName() work without characterizing it in the capacity.

PHP code to discover aggregate of two numbers by getting to worldwide variables utilizing $GLOBALS

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

Output:

60

In the code above, num1 and num2 are worldwide variables so we are getting to them utilizing $GLOBALS, and aggregate is a variable present inside $GLOBALS, in this manner, it is available from outside the capacity too.

Leave a Comment

error: Alert: Content is protected!!