PHP

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 🙂

Nachiket Panchal

Founder & Administrator of `errorsea` Having interest in Programming & Technology.

Recent Posts

5 Important Things To Know About WordPress Before You Use It

There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…

3 years ago

How to Install MySQL on Your PC in 3 Easy Steps

In this tutorial, I'm going to show you how to install MySQL on your computer.…

5 years ago

Download and Install Turbo C++ for Windows 10 (Full Installation Guide)

Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…

5 years ago

PHP .HTACCESS Redirects

We can redirect any webpage to any other or redirect the whole domain or website…

5 years ago

PHP Redirect Pages

There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…

5 years ago

PHP Include & Required

Include files in PHP are used in appending various global or config files. We can…

5 years ago