#native_company# #native_desc#

Object Oriented Programming in PHP: The Way to Large PHP Projects Page 8

By Luis Argerich
on January 25, 2008

Using Classes to Manipulate Stored Data

One very nice thing of PHP and OOP is that you can easily define classes to manipulate
certain things and the call the appropiate classes whenever you want. Suposse you have
a html form where the user selects a product by selecting it’s product ID, you have
the data of the products in a database and you want to display the product, show its
price, etc etc. You have products of different types, and the same action might have
different meanings for different kind of products. For example showing a sound might
mean playing it while for some other kind of products might mean to display a picture
stored in the database. You might use OOP and PHP to code less and code better:
Define a class product, define which methods the class should have (example display),
then define classes for each type of product which extends the product class (class
SoundItem, class ViewableItem, etc…) override the methods you define in product
in each of this classes make them do what you want.
Name the classes according to the “type” column you store in the database for each
product a typical product table might have (id,type,price,description,etc etc)…
Then in the processing script you can retrieve the type from the database and
instanciate an object of the class named type using:


$obj=new $type();



This is a very nice feature of PHP, you might then call the display method of
$obj or any other method regardless the type of object you have. With this technique
you don’t have to touch the processing script when you add a new type of object,
just add a class to handle it.
This is quite powerful, just define the methods all objects regardless of its
type should have, implement them in different ways in different classes and use
them for any type of object in the main script, no ifs, no 2 programmers in the
same file, eternal happiness.
Do you agree programming is easy, mainteinance is cheaper and reusability is real now?
If you command a group of programmers is easy to divide the tasks, each one might
be responsable for a type of object and the class that handles it.
Internacionalization can be done using this technique, apply the proper class according
to a language field selected by the user, etc.

Copying and Cloning

When you create an object $obj you can copy the object by doing $obj2=$obj, the new
object is a copy (not a reference) of $obj so it has the state $obj had in the moment
the assignment was made. Sometimes you don’t want this, you just want to create a
new object of the same class as obj, calling the constructor of the new object as
if you had used the new statement. This can be done in PHP using serialization and
a base class that all other classes must extend.