Introduction
The custom class below is an alternative to using PHP
global variables. It is safe to use this class to control globals being defined once for the application. You can also access the globals within classes and methods without the global identifier.
Background
I created this custom class, because I needed a way to store my globals without being changed by third party code. It achieves this by using PHP
Late Static Bindings with self and static declarations.
Custom Class for Handling Globals
if(!class_exists('globals'))
{
class globals
{
private static $vars = array();
public static function set($_name, $_value)
{
if(array_key_exists($_name, self::$vars))
{
throw new Exception('globals::set("' . $_name . '") - Argument already exists and cannot be redefined!');
}
else
{
self::$vars[$_name] = $_value;
}
}
public static function get($_name)
{
if(array_key_exists($_name, self::$vars))
{
return self::$vars[$_name];
}
else
{
throw new Exception('globals::get("' . $_name . '") - Argument does not exist in globals!');
}
}
}
}
How to Define Global
Here is an example of how to define a simple and complex global.
globals::set('website','codeproject');
globals::set('SERVER', array(
'REMOTE_ADDR' => filter_input(INPUT_SERVER, 'REMOTE_ADDR'),
'PHP_SELF' => filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_URL)
));
How to Use on Line, Method or Class
The below examples will show you how to use it in your code.
echo globals::get('website');
function getwebsite()
{
echo globals::get('website');
}
class websites
{
public function getwebsite()
{
return globals::get('website');
}
}
$websites = new websites();
echo $websites->getwebsite();
$SERVER = globals::get('SERVER');
echo $SERVER['PHP_SELF'];
echo globals::get('SERVER')['PHP_SELF'];
Global Variable Redefinition
Once a global variable has been defined, it cannot be changed. So if you define an array, it has to be all at once. The example below shows this.
globals::set('website','codeproject');
echo globals::get('website');
globals::set('website','google');
echo globals::get('website');
Conclusion
I hope this code saves you development time. :)