Beginner PHP Programmer Mistakes Part One: Using Global Variables
I’ve talked about PHP before. One of the major problems is all the beginners writing code and posting examples that other beginning programmers use. But complaining on and on about beginner code isn’t actually very useful. What if I actually explained how to write good code in PHP and what sort of code that a PHP programmer should avoid? Well, that would actually be useful. That would accomplish something. That would be another series of posts at CodingExperiments.
So, here goes. This post in the series will cover using global variables in PHP, or rather, why you shouldn’t use global variables in PHP. First, let’s see what a global variable is, and what it does.
<?php
$random_variable = 'foo';
$awesome_variable = 'http://codingexperiments.com';
// This works
function bar ()
{
// Making it global makes it work
global $random_variable;
echo $random_variable;
}
bar ();
//
// This doesn't
function website_promotion ()
{
// $awesome_variable is not being made global here
echo '
' . $awesome_variable;
}
website_promotion ();
?>
If you were to run that script, you would get “foo”, and only “foo”. Don’t believe me? Try it out here. Any good programmer will tell you that the URL of this awesome website isn’t being displayed because of scope. Read more about PHP variable scope here.
So, why are global variables bad? Because they can be changed from anywhere. Global variables are often used for configuration settings, as they will be needed in many places in the program. Configuration settings typically should never change. That’s why PHP constants are a very good alternative for configuration settings.
If you want a read that really goes in-depth about global variables and so forth, you can check out “Why Global Variables in PHP is Bad Programming Practice“
Posted in PHP, Uncategorized | View Comments