The dangers of global variables revisited because of PHP.

In 1985 after about two years of full time programming I had an epiphany; realising that global variables are a very bad idea. Roughly 20% of the bugs that I kept finding were down to abuse or misuse of global variables, so I stopped using them, apart from the time when you really should use one (e.g. for a pointer to global shared memory that never changes).

So here I am over 20 years later, and I've just realised exactly the same thing, except this time it's in PHP not 'CORAL' '66'.

I wondered how this happened and it dawned on me that it's a result of the way that I originally learnt PHP - taking over someone else's code. They used globals, lots of examples use globals, and in a way it seems to be the way that things are done. I should have known better.

The problem is worse with PHP than before, as failing to declare a global variable using the global keyword just lets PHP invent a local one - and then the code fails, possibly silently.

Functions that provide access to the data is the solution that I adopted back in 1985, and it works just as well today. Hand in hand with this is the migration of the config.php approach, currently my config.php only contains the db connection details, the rest of the site configuration comes from a table, usually with a default value and a specific value to allow test & live sites to be configured differently.

So, instead of having

class ShowUser
{
    function output()
    {
        global $config;
        if ($config['allow-view'] == 1)
            echo "Stuff";
    }
}

the code is shorter, possibly more legible - and easier to maintain, for all the reasons that it was when I first thought of it.

class ShowUser
{
    function output()
    {
        if (get_from_config('allow-view') == 1)
            echo "Stuff";
    }
}

Usually I don't need to have a global for the DB - PHP hides that from me, and as most of the time one only needs one database connection, there is no need to wrap this up.

So it's just the config and the session that need functions - a total of four functions and much nicer code. I'm happy again.