Category Archives: Variables

Removing the bad smell of global variables

There is always a lot of discussion about good coding practice in PHP, and considerable disagreement when it comes to some areas.

It can be really quite confusing, especially when learning PHP, and many of us just take the easy option because we can’t find agreement on an alternative.

Fortunately, there are some areas where there is general consensus on the best way forward. Global variables is one such area.

Why shouldn’t I use global variables?

While using global variables can seem very easy and convenient, they are often viewed as bad coding practice in PHP for several reasons:

  • They make debugging harder
  • You can get  unexpected results if they are modified without other parts of the code knowing
  • It can make code less portable
  • Security can be compromised

What’s that smell?

So, global variables can lead to a bad code smell and we all know that everyone wants to avoid unmanageable and badly designed code.

But what’s the alternative?

Keeping it simple

One of the easiest ways is to pass the values to your function using parameters. So instead of code that uses global variables like this:

 

We can pass values to the function like this…

 

Here, the variables are local only to the function and this makes debugging in particular, much much easier.


Whether you found this post removed a bad smell for you, or made you smile knowingly, sign up to my newsletter to make sure you get all the latest tips in your inbox: