PHP.GT

Understanding the ProtectedGlobal object

ProtectedGlobal is the object that replaces the original superglobal arrays after protection has been enabled.

Its job is deliberately simple: allow access to a small internal whitelist, and throw an exception for everything else.

Array-style access

The class implements ArrayAccess, so it can be used with normal array syntax:

$value = $_COOKIE["XDEBUG_SESSION"];
isset($_ENV["APP_ENV"]);
$_ENV["APP_ENV"] = "development";
unset($_ENV["APP_ENV"]);

Those operations are only allowed for offsets that were whitelisted earlier.

Blocked access throws an exception

If code tries to read, write, check, or unset a non-whitelisted offset, the object throws GT\ProtectedGlobal\ProtectedGlobalException.

$page = $_GET["page"]; // Throws when "page" was not whitelisted.

This is the core behaviour of the library. It does not silently return null, and it does not log a warning while continuing. It fails loudly so the accidental dependency can be fixed.

Allowed offsets remain mutable

When an offset is whitelisted, the value can still be updated or unset through the ProtectedGlobal object:

$_ENV["APP_ENV"] = "production";
unset($_ENV["APP_ENV"]);

That behaviour is useful for compatibility, but in new code it is still usually better to avoid mutating global state where possible.

Debug output

If a protected global is converted to a string or dumped in a debugger, the object exposes a warning message instead of pretending to be a normal array.

That makes mistakes more obvious during development:

echo $_GET;
var_dump($_GET);

The object includes the warning text and any whitelisted values in its debug information.


Next: API reference