HomePHP Handling MySQL Data Sets with Static Variables in PHP 5
Handling MySQL Data Sets with Static Variables in PHP 5
In this second part of a four-part series, I finish building a sample MySQL driver by adding to it a whole new class responsible for iterating over database result sets through a friendly and intuitive API. This functional example shows that the use of a simple static property makes it easier to implement the Singleton pattern, which is convenient when developing a class that abstracts the access to a database server, be it MySQL or a different one.
Understanding the behavior of static class properties in PHP 5 is a straightforward process that can be tackled with minor headaches, even for inexperienced developers taking their first steps into the huge and sometimes esoteric field of object-oriented programming.
And the reason for this is simple: essentially, a static property is only an in-memory place thatís shared by all of the instances spawned from the same originating class. This means that any value assigned to that property can also be accessed and modified by those instances.
While at first sight, this is not especially interesting, it must be said that static properties do play a relevant role in the way that classes behave and carry data. In many cases, though, itís far easier to explain the rationale behind this kind of property than to show or recreate from scratch a real-world scenario where they can be seen in action.
Bearing in mind that you may want to see an example that shows how to use static class variables in a concrete and realistic case, in this group of tutorials youíll learn how to build an extensible MySQL driver. This driver will employ a few static properties to behave like a Singleton class, and to improve the way that it connects to the RDBMS as well.
In the introductory chapter of this series, I started off developing the first component of the MySQL driver, which turns out to be a basic class that acts like a wrapper for the native MySQLi class included with PHP 5. However, the most important thing to notice here is that this component uses a static $_instance property to turn the driver into a Singleton, which prevents us from dealing with multiple instances of it.
The driver in its current state is only capable of opening and closing a connection to the server, and running hard-coded SQL queries, so itís desirable to provide it with more functionality. Therefore, in this second part of the series Iím going to add to the driver a second component. It will be comprised of a separate class, responsible for handling result sets through a simple API.
Ready to learn the full details regarding the construction of this data set processing class? Then start reading right away!