Redgard
Redgard

Reputation: 39

Superglobals vs $GLOBALS visibility in PHP

here is how Superglobals are defined in PHP

Superglobals — Built-in variables that are always available in all scopes

And here is how $GLOBALS are defined here

$GLOBALS — References all variables available in global scope

I'm aware of the existence of 'various' scopes like local, static, closure, namespace and maybe more in PHP and I'm not looking for a reason to nitpick wording inaccuracies in the definitions. However I wonder why $GLOBALS was defined differently from Superglobals in terms of availability, not this way:

$GLOBALS — References all variables available in all scopes

Upvotes: 0

Views: 45

Answers (1)

ADyson
ADyson

Reputation: 62078

There is no difference in their visibility. $GLOBALS is a superglobal as well. This means that you can access that $GLOBALS from variable anywhere in your code, in any scope.

Regarding your confusion, I think you've misunderstood what the documentation is telling you.

The bit from the documentation of $GLOBALS that you quoted:

$GLOBALS — References all variables available in global scope

isn't talking about the availability of $GLOBALS itself (that's already described in the superglobals documentation).

Instead it's telling you what the contents of $GLOBALS is. What $GLOBALS contains is all variables which have global scope.

And the fact that they're referenced by $GLOBALS then gives you a nice way to read them from any scope, not just the global scope (this removes the need for you to write things like global $variable; for every global you want to reference inside a function, for example). Note that as of PHP 8.1, $GLOBALS, global variables cannot be modified via it - so it provides a read-only view of those values.

Upvotes: 1

Related Questions