Variables and Location, Location Location

While taking a review class on PHP, I heard the most ridiculous thing imaginable about variables… All the variables should be declared at the top of the first PHP tag or at the top of the page… Lets dig into this and see….

According to Code Complete: A Practical Handbook of Software Construction, Second Edition, you want to make the life of the variable as short as possible, (I mentioned this in my previous post Function Layouts, the best number of functions, and it still holds true today, but lets look at some of the Pro’s and Con’s.

So the concept is that if all the variables are defined at the top, that makes it very easy to locate them and change them if necessary. This seems fairly awesome, for small pages and infrastructures, however, the larger constructs will have some serious issues. Let’s assume that we have a page that is over 1,000 lines of code, all mixed with PHP and HTML, at the top is over 100 lines of code defining variables and values associated with those variables, and then the we decide to add a new variable that is used somewhere in the middle of the page. Making the change to it at the top makes crystal clear idea, going down to the place where we want to inject the code to read that variable is easy, but we then launch the page and we find out that the value that is presented to us is not the value we inserted into the code. The variable name we chose is already in use (if we bothered to read all 100 lines of code, we would have found it, perhaps a positive for keeping them all in the same place).

Take that same concept, and if we went down to the area that the variable was expected to be defined, we inject the variable, the output and usage within a short period of time, we risk overriding an already existing variable too, but we know the section of code we are working on is working fine. If the entire page also contains this limited scope and short time, the probability of the problems caused by our variable injection is lowered (not completely removed, but much lower).

With that same concept, if we have to change the value of that variable (if it already exists) we go searching for the surrounding text within the code and move upwards (hopefully very short distance) versus hunting through 100 lines of code that are mushed together for all variables.

Another positive take away of the Short Life concept, if we decide to later on refactor the section of code (say into an require_once event) having that variable close at hand will easily be found to be incorporated to the secondary file.

Until next time, Happy Coding and may you be blessed!

Leave a Reply

Your email address will not be published. Required fields are marked *