PHP DevCenter
oreilly.comSafari Books Online.Conferences.


The Practicality of OO PHP
Pages: 1, 2, 3


My data extraction class has a flaw. My example class groups the HTML output into an array. This array, being associative, can hold only one row of data from the same database table. Entering a second row of data (from the same database table as the first row) into the array overwrites the original row. Additionally, entering data from a second (different) table that contains one or more columns with identical names as in the first table will override the data from the first table. I could have prevented this with better programming, but I want to show you an example of how I can fix this without having to modify code. This is where multiplicity comes in handy.

Multiplicity is the practice of using multiple instances of the same class. In this case it increases productivity because there is no need to do extra programming. For example, suppose that you need to say hello to two users instead of one. The siteaimproved.php code includes:


$data1 = new DataExtraction();
$data2 = new DataExtraction();

$data1->deWhereStatement("WHERE id = '2'")
$data1->deExtractDataHtml("users_table", "id", "username", "email");

$data2->deWhereStatement("WHERE id = '3'")
$data2->deExtractDataHtml("users_table", "id", "username", "email");

echo("Hello, ".$data1->deGetData("username")."! ");
echo("Hello, ".$data2->deGetData("username")."!");

Assuming "TestUser" has an ID of 2 and "AnotherUser" has an ID of 3 in the users_table table, that will output the text Hello, TestUser! Hello, AnotherUser!

As you can see, by instantiating a second instance of the class, you can now have multiple rows of data from the same database table. The second instance of the class is a separate object and exists independently of the first. Keep in mind that this might start to hog system resources if you need to call thousand of rows that need to instantiate thousands of objects. You probably wouldn't use this class in such a way, though. I'm simply trying to illustrate a point.


Suppose that a new project comes along. It uses Flash and needs to display one row of information from a database. You could create an entirely new set of code and spend a ridiculous amount of time reprogramming old functions, or you could modify the original class. Here's a new function to add into dataextractionclass.php:

// Usage deExtractDataFlash("db_table", "field1", "field2", "field3")
function deExtractDataFlash($table)       
    $args = func_get_args();
    foreach($args as $k=>$v)
       if($k != 0)
         $fields .= trim($v).", ";
    //takes off the trailing comma and whitespace       
    $fields = substr($fields, 0, (strlen($fields) - 2));        

    $query  = "SELECT $fields FROM $table $this->whereStatement";
    //Ex: WHERE waterId='1'
    //calls another class within this class
    $result = mysql_query($query) or die("MySQL Query Error: ".mysql_error());
    while($row = mysql_fetch_array($result))
        foreach($args as $k=>$v)
           if($k != 0)
                      //outputs in flash variable format

You can now call this function from the original dataextractionclass.php class and use it in conjunction with Flash movie files. All that you have to do is insert the new function into the original class file. Sometimes you will find the need to keep your original class intact without changes. In that case, use the keyword extends to add to an existing class without having to modify its file.

For example, the original class name is DataExtraction. Use extends to avoid changing the original class file like so:

class FlashExtraction extends DataExtraction

/* Flash Extraction Function Here */


Class extensions, unlike class functions, can go within separate files. In order to take advantage of this technique, however, keep in mind that you must define or include the original class within your PHP page before the class extension. For more in-depth info on PHP classes, refer to the official PHP documentation.


OO PHP is a great way to keep your files structured and organized. Instead of entire code structures being embedded and spread out over numerous HTML pages, a single class file can dissolve the chaos. When modifying code, instead of having to go to every page to change a variable or add an equation, you only have to modify the class file. The fewer files you have cluttered on your web server, the less likely you will be to freak out when it's time to make a change. Those of us with IT jobs aren't usually the most organized, so any little bit of organization with file structure helps. This also is a factor of productivity as well as efficiency.


OO PHP can increase efficiency dramatically. What do I mean? In this case, it's the integrity of the code--having a finished project with minimal errors. If you have to reuse functions that you have embedded within HTML, chances are good that you may have left out or forgotten some code--it's like losing a sock when you put it in the laundry. With OO PHP, however, the code stays within one file and there is minimal chance that the code will have changed, because all you need to do is transfer the file. Going back to the laundry analogy, this is similar to putting your socks in their own load, where it is easier to keep them all together.

The One Downside to OO PHP

I don't want to be totally biased about OO PHP. There is a disadvantage of using it. Honestly, there aren't many disadvantages to OO PHP, but one sticks out the most: time. It tends to take a little longer to program a class in PHP--in general, not just depending on your skill level. However, your productivity and efficiency increases immediately the next time you use the class. This should really help you decide whether to use OO PHP for certain projects, as I mentioned earlier.

If you need to reuse the code in similar projects, OO PHP is definitely the way to go; however, if you are short on time and will never use the code again, OO PHP may not be a wise choice.

There also is a slight learning curve to using OO PHP. It's nothing drastic, but if you've never worked with classes before or are new to programming, OO PHP may take a little while to get used to.


I hope that you can walk away from reading this with a newfound technique to improve your PHP coding experience. That said, it's important to remember that OO PHP is just a technique. It's not the end-all of other forms of coding. It's another tool in your proverbial toolbox. It's up to you and your good judgment to know whether OO PHP is the right tool to help construct your current project.

Example files are available here.

David Day is the founder of Geekmatics, a company that provides digital business solutions and home PC essentials.

Return to the PHP DevCenter.

Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!

Sponsored by: