Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / PHP
Tip/Trick

PHP Global Variable Alternative

Rate me:
Please Sign up or sign in to vote.
4.86/5 (3 votes)
21 May 2014CPOL 17.6K   3
A new way to handle globals in php without declaring global identifier.

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

PHP
if(!class_exists('globals'))
{
    // Handles all the globals for the page.
    class globals 
    {
        private static $vars = array();

        // Sets the global one time.
        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;
            }
        }

        // Get the global to use.
        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.

PHP
// Simple Definition
globals::set('website','codeproject');

// Complex Definition with Array
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.

PHP
// Using Outside Class
echo globals::get('website');

// Using in Method
function getwebsite()
{
  echo globals::get('website');
}

// Using in Class
class websites
{
  public function getwebsite()
  {
    return globals::get('website');
  }
}

$websites = new websites();
echo $websites->getwebsite();

// Using Global Array Definition
$SERVER = globals::get('SERVER');
echo $SERVER['PHP_SELF'];

// OR Directly in PHP 5.4
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.

PHP
// Define Once
globals::set('website','codeproject');

// Get should be codeproject 
echo globals::get('website');

// Define Twice
globals::set('website','google');

// Get should still be codeproject
echo globals::get('website');

Conclusion

I hope this code saves you development time. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Codevendor
United States United States
Please visit my personal website https://codevendor.com for my latest codes and updates.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Maykonn Welington Candido22-May-14 5:42
professionalMaykonn Welington Candido22-May-14 5:42 
GeneralRe: My vote of 3 Pin
M@dHatter22-May-14 23:08
M@dHatter22-May-14 23:08 
GeneralRe: My vote of 3 Pin
Maykonn Welington Candido23-May-14 2:39
professionalMaykonn Welington Candido23-May-14 2:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.