In this first part of a four-part series, I show you how the declaration and further use of a single static property inside a MySQL abstraction class can be really useful for turning this class into a Singleton. While it’s fair to say that you can use different approaches for implementing this design pattern, most of them will employ a static variable.
Without starting a debate about the strengths and weaknesses of PHP 5, I'd like to say that the language, with all its cons and pros, has reached a great level of maturity, particularly when it comes to evaluating its highly-enhanced object model.
Well-known improvements like member visibility and abstract classes, coupled to a native support for interfaces and exceptions, just to name a few examples, provide developers with a set of powerful characteristics that allow them to build more complete object-oriented web applications. Best of all, they can do this without needing to appeal to tricky and dirty programming hacks, used pretty frequently in the bad old days of PHP 4.
Of course, with the variety of eye-catching features packaged behind a friendly API, it's not surprising to see that the use of static variables has been delegated in many cases to the entrance of a humble backdoor. In reality, static variables (or class-level variables, as some programmers use to say in meetings to create a stronger impression on the people around them) are indispensable, especially if your PHP programs implement some common design patterns such as Singleton and Lazy Loading.
Naturally, as with many other native features of PHP, when misused or overused, static variables can lead quickly to poorly-written, messed-up code, which can be a nightmare to maintain and scale. But, as you may guess, this is simply a consequence of their bad usage and not of the variables' intrinsic nature.
As I said a moment ago, static variables can be really helpful when used in a clever way, and to prove that, in this group of articles I'm going to show you how to utilize them in the development of a basic - yet functional -- MySQL driver. This driver, through a simple set of methods, will permit us to perform a few handy operations against a selected database, such as running queries, manipulating data sets, and so forth.
The didactic facet of this experience won't be building a driver like this; instead, it'll be aimed at demonstrating how the use of some static variables can remarkably improve the behavior of the driver.
Now, join me in this hopefully educational journey and start rediscovering the real power behind using static variables in PHP 5. Let's jump in!