What Is GLOBALS in PHP, and How to Use $GLOBALS in PHP

Global is used to declare a superglobal variable that can be accessed in all scopes.

What is $GLOBALS in PHP?

$GLOBALS is used to access global variables in PHP. We can use $GLOBALS in all methods and functions to access global variables within the PHP script.

When to use $GLOBALS?

Sometimes we have to access global variables in a particular function or method without passing it as an argument. At that time, we can use $GLOBALS superglobal.

How to use $GLOBALS?

All global variables are stored in $GLOBALS array in PHP. We can access any global variable in the PHP script via its variable name in the $GLOBALS variable.

Syntax

$GLOBALS['variable_name'];

Example 1

<?php
$name = "errorsea.com";

function globals_example() {
$GLOBALS['result'] = "Visit ".$GLOBALS['name']." to learn amazing programming concepts meticulously";
}

globals_example();
echo $result;
?>

We can also access array variables via $GLOBALS.

Example 2

<?php
$links = ["errorsea.com","google.com"];

function globals_array_example() {
$GLOBALS['result'] = "Visit ".$GLOBALS['links'][0]." to unveil fascinating coding skills rather than searching at ".$GLOBALS['links'][1];
}

globals_array_example();
echo $result;
?>

Conclusion

We can access any variable within the PHP script in any function or method. In addition, we can also declare a global variable in a method or function without passing any reference.

I hope you found this post interesting.

Enjoy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *