How Object Oriented Programming Applies to PHP

Album Cover: Flight of the Conchords

"She's so hot, she's making me sexist."
Flight of the Conchords / Boom

Posted on February 09, 2005 4:04 PM in Web Development
Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

Back in November, Richard asked for a real world explanation of how OOP can be applied to PHP on an e-commerce site. In the months since his imploration, I've been mulling over several possible methods of providing an answer. Not until today did I decide to give an explanation in the simplest of terms.

OOP should be applied to PHP on an e-commerce site for the same reason it should be applied to any other site written in PHP – or any application written in a language that supports OOP for that matter. OOP allows for modularization of code and simplification of development.

While sites like A Beginner's Crash Course into Object Oriented Programming give great insight into what OOP is, they do a poor job of conveying why OOP is important.

It's as simple as this: If you have a class that envelops all the functionality and/or information associated with the products you are selling, you can reuse that class throughout your site. Define it in one single place and reuse it everywhere. Derive new classes from that class, share that class with other e-commerce sites you maintain, and realize just how powerful OOP can be.

Consider the following example, which utilizes OOP:

<?
$product1 = new Product("Chapstick", 0.99, 3);
$product2 = new Product("Tater Tots", 2.99, 1);
$total_price = $product1->GetPrice() + $product2->GetPrice();
?>

Then consider the following example, which does not:

<?
$product1_name = "Chapstick";
$product1_price = 0.99;
$product1_quantity = 3;
$product2_name = "Tater Tots";
$product2_price = 2.99;
$product2_quantity = 1;
$total_price1 = $product1_price * $product1_quantity;
$total_price2 = $product2_price * $product2_quantity;
$total_price = $total_price1 + $total_price2;
?>

Even at this granular level, it's easy to see how OOP can help you to save time (its reusable) and space (less code).

I'd love to hear from others out there who have applied OOP to their PHP apps. There are surely better real-world examples of how OOP techniques can be applied to the benefit of the developer.

Comments

No one has added any comments.

Post Comments

If you feel like commenting on the above item, use the form below. Your email address will be used for personal contact reasons only, and will not be shown on this website.

Name:

Email Address:

Website:

Comments:

Check this box if you hate spam.