ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


The Practicality of OO PHP

by David Day
07/28/2005

There seems to be a common pitfall among some PHP developers--especially those just beginning PHP programming--and that is their lack of object-oriented (OO) PHP use. This article's purpose is to inform developers about the practicality of OO PHP; fully understanding the benefits of using OO PHP should be a requirement in the PHP learning process.

Pitfall Among Developers

I myself experienced the pitfall in the beginning of my PHP enlightenment, but the light shone again and my eyes opened to the use of OO PHP. What I mean by OO PHP specifically is the use of classes, not just simple function blocks. Many new developers feel that classes are useless, cumbersome, and time-consuming. Given the unique nature of how PHP actually works, it is possible to throw functions in the code at any point on the page and start using them immediately. If this is the case, it is possible to include a page of functions at the top of the page and go to town with them. Now, while it is possible to do this--and using classes isn't very far from it in some aspects--there are numerous benefits and advantages to actually using classes instead of simply using a list of functions.

What PHP Objects Are All About

To new developers, classes--or object-oriented programming, for that matter--may seem a little intimidating or unfamiliar. For those of you who aren't familiar with classes, here's a brief introduction.

Please note that PHP 5 has a new Object Model from PHP 4. This section refers to PHP 4, so if you have upgraded to the new version of PHP, please refer to the official PHP documentation.

Here's a file called exampleclass.php. Class definition looks like this:

<?php
class Example
{
    //class-wide variables
    var $var1;
    var $var2;
         
    //function to gather two numbers
    function set_numbers($number1, $number2)
    {
        $this->var1 = $number1;
        $this->var2 = $number2;
    }
         
    //function to add numbers together
    function add_numbers()
    {
        return ($this->var1 + $this->var2);
    }        
}
?>

Under the class-wide variables comment are two variable initializations: var $var1; and var $var2;. Variables defined in this manner are available throughout the entire class. You can access them in any function by using the syntax $this->variablename.

For example, the function set_numbers() assigns the $number1 argument to the classwide variable var1. The function add_numbers() returns the sum of var1 and var2.

To use this class, create an instance of the Example class object (exampleuse.php):

<?php
/* Include the class file using require_once. 
It will require the class to be loaded (or
the page won't load), and will only allow 
it to be included once, to avoid errors. You
can also use require(), include(), or 
include_once() */

require_once("exampleclass.php");

//create an object variable for the instance
//of the example object

$exampleobject = new Example;

This creates an object variable using the new function. The syntax is simple: $objectvariable = new ClassName;. As you can see, the name of the class in exampleclass.php is Example; this is the name you must use to assign the class to the object variable. With an instance of the Example class, you can use the functions (or methods) inside of it:

$exampleobject->set_numbers(1,3);
echo($exampleobject->add_numbers());

//the output will be: 4

?>

Using class methods is very similar to the $this-> operator, except that $this is replaced with the object variable. In this example, the object variable is $exampleobject. Both $exampleobject->set_numbers(1,3) and $exampleobject->add_numbers() call methods in this instance of the Example class.

For more in-depth info on PHP classes, please refer to the official PHP documentation.

PHP Pocket Reference

Related Reading

PHP Pocket Reference
By Rasmus Lerdorf

Should I Use OO PHP?

There are several factors that should determine whether you use OO PHP. For instance, some projects may require the use of OO PHP to ensure a successful completion, while in others, using OO PHP is not required and would only burden the workload.

When should you use OO PHP? When you:

When should you not use OO PHP? When you:

These are just suggestions. Use your own judgment when determining whether to use OO PHP. There are a million ways to skin a cat, and the same principle is true with programming: use whatever method works best for you (and those who have to read your code later). There truly are some major benefits to working with OO PHP, however.

Benefits of OO PHP

Among the numerous benefits of using OO PHP, the three that stand out are productivity, organization, and efficiency. With productivity, OO PHP can save time or increase workflow. For organization, OO PHP can keep your code and files organized. By efficiency, OO PHP can make your project and future projects run smoothly.

Productivity

The primary benefit of using OO PHP is the increase in productivity. By this I mean you can save time or boost your workflow. After you create a class file, the next time you use it in a project you've automatically increased productivity, because you've saved the time of having to go back and reprogram something. Now you may think that a list of functions is good enough to save you time--again, I was victim to this early on--but eventually you will find that you could have better used the time spent customizing the function list specifically for the new project. In most cases, a simple class list, carefully programmed, can save you multiple hours of programming repetitive (not to mention really boring) code.

Here are a few examples of productivity that use a small database extraction tool that I whipped up a while back. It originally extracted a single row into a format that a Flash file could read, but I later expanded it for HTML output (having tired of typing repetitive SQL statements). For the sake of having a more interesting example progression, assume that the class starts off with the HTML output ability only. You can download this example class and support files at the end of this article.

Reusability

Reusability in this case is the process of using the same class file for multiple projects. Have you ever needed to reuse your code for another project? Most developers have, and, believe it or not, sometimes it's hard to port your code from one project to another. Functions could be spread out over multiple pages, or complex code could be embedded within HTML, or other various nuisances could make it hard for a smooth reuse of your code. There is a solution with OO PHP.

The process of instantiating classes provides an easy way to implement existing code into a new or already existing project. You don't have to skim through line upon line of existing code to pull out the little snippets needed for your project to function properly. All of your code is within a single file that you can easily include on any page and put to use.

For example, suppose you are using my Data Extraction class for web site A (sitea.php):

<?php
require_once("dataextractionclass.php");

$data = new DataExtraction();

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

echo("Hello, ".$test->deGetData("username")."!");
?>

Assuming the user "TestUser" has an ID of 2 in the users_table table, this will output the text Hello, TestUser! If a web site calls for a similar approach in terms of requesting quick information from a web site, you can simply reuse it.

The next example is from web site B (siteb.php):

<?php
require_once("dataextractionclass.php");

$data = new DataExtraction();

$data->deWhereStatement("WHERE email = 'test@example.com'")
$data->deExtractDataHtml("clientlist_table", "id", "email", "balance");

echo("The balance for ".$test->deGetData("email"));
echo(" is $".$test->deGetData("balance")."!");
?>

Assuming the email address test@example.com is in the clientlist_table table with a balance of $2,041, this will output The balance for test@example.com is $2041!

As you can see, OO PHP provides a quick and easy outlet for reusing code.

Multiplicity

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:

<?php
require_once("dataextractionclass.php");

$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.

Versatility

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'
                
    $this->dbDataExtraction->dbConnect_Db();
    //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
              echo("&".$v."=".$row[$k-1]);
           }
        }
    }
}

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:

<?php
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.

Organization

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.

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.

Conclusion

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.

Copyright © 2009 O'Reilly Media, Inc.