When should objects be used in PHP?

I’ve read a few books about PHP and am learning it while working on a project. I’m confused about objects in PHP. The examples I read come with analogies like a car and its parts etc. I can’t figure out how objects can be used in a real project. Can someone guide me about this? In which situations would you use OOPs to make a task easier?

If this question has been covered here in some sticky thread already, could you please point me to it.

Thank you.

The ablility to create objects in php is an extremely powerful feature.

Anthony has provided a good example, but it is important to realise the power of object orientated programming, especially with regards to inheritance. I.E. One object can inherit properties from another.

Object Orientated Programming is not specific to PHP and to get a good grasp of it you might want to have a look at how Java works as OOP forms the basis of programming in Java.

Here’s a quick example where things are made easier.


<?php
# finds, updates and saves car objects
$mapper = new CarMapper;

#find a car
$car = $mapper->findById(45);

#set the driver of the car, a driver object
$car->setDriver($driver);

#save the modified car
$mapper->save($car);
?>

Of course there are lots of lines of code hidden away which implement the functionality, but we used 4 lines of code there to find a car, change it, and save it.

Powerful stuff, and much easier to read too. :slight_smile:

Thanks guys. I found a tutorial on this.