Article
Object Oriented PHP: Paging Result Sets
If as a PHP developer you find yourself writing the same code again and again, or dealing with an increasingly stifling array of custom functions and include files in your script, it's probably time you looked into Object Oriented Programming (OOP). OOP has truly come into its own over the past 5 years or so. The world over, application and Web developers alike have discovered the merits of this type of software design, and now it's your turn!
In this article, I'll teach you the basic principles and features of Object Oriented Programming that exist in the PHP language, and take you through a few simple examples so you can see how it all works. We'll then take this newfound knowledge and apply it to a practical problem. Together, we'll create a reusable component that will handle the splitting of MySQL result sets into pages.
Buckle up; I see objects on the road ahead -- it's going to be a bumpy ride!
What's the Big Idea?
Although Object Oriented Programming itself is not always simple, the main idea behind it is fairly easy to grasp.
The primary goal of Object Oriented Programming is to bind together data (in the form of variables) with the code that is responsible for working with them.
So instead of having one big mess of variables with one big mess of PHP code, OOP would have you break down your problem into smaller (and, ideally, more organized) bundles of variables and code. These bundles can then work together to produce the desired effect. If you do your job really well, you can even take some of those bundles and drop them right into another project down the line and save yourself the trouble of re-developing that functionality the next time you need it.
So just so we're clear, OOP doesn't actually allow you to do anything you couldn't already do with big messes of code and variables; it's really just a more organized way of working. And if you're anything like me, your PHP scripts could use all the help they can get in the organization department!
So let's say you're sick of writing database connection code every time you develop a new database-driven Web site in PHP. You could combine all of the variables (username, password, hostname, database name, etc.) and all the code (connecting to the database server, selecting a database, checking for errors, etc.) involved in your database connection into a single package, called an object. You can then use that object to handle your database connection from then on.
Kevin began developing for the Web in 1995 and is a highly respected technical author. He wrote