HomePHP Improving MySQL Connection with Static Variables in PHP 5 Classes
Improving MySQL Connection with Static Variables in PHP 5 Classes
In this third part of a four-part series on static variables, I show how to use another static property in the previous MySQL driver to connect “more cleverly” to the database server. This example demonstrates how powerful a property like this can be, when utilized in an effective manner.
While at a glance the subject may seem rather irrelevant and even pretty boring, the truth is that the proper use of static variables in PHP 5 classes can be of great help in improving the way that they perform certain tasks and their relationship in a given application context.
Thus, if you're a PHP developer who wishes to see how to utilize static properties in a real-world scenario, then this series of articles may be what you're looking for. It teaches how to build a functional object-oriented MySQL driver, which will employ a couple of class-level variables to reduce the instantiation of objects and connect to MySQL more efficiently.
Now that you know what to expect from this series, I'd like to spend a few moments reviewing the concepts discussed in the previous part. In that article I finished building the aforementioned MySQL driver by appending to it a class exclusively responsible for handling result sets.
With the addition of this class, I was able to code a script that used a Singleton instance of the driver first for connecting to the server, then for selecting a specified database, and finally for fetching records from a fictional "users" table. At the end of its execution, the script also showed how to use the functionality of the driver to iterate over those records via a simple "foreach" construct. In short, the script was simple and effective.
Of course, the driver should be considered and evaluated as to what it really is: an example. Its development demonstrated how a simple static property can be used for turning a whole class into a Singleton -- which is useful when working with a database handler object like the one mentioned above.
Due to their nature, however, static variables can be utilized in multiple contexts and with purposes other than building Singleton classes. With that idea in mind, I'm going to show how to use yet another variable to improve the way that the driver establishes a lazy connection to MySQL.
The experience will be really educational, trust me. So join me in this third part of the series and begin reading right now!