Chapter 8. Object-Oriented PHP

Before PHP 5 came along, object-oriented programming (OOP) support in PHP was more of a hack than a serious attempt. As a result, the few who used it often regretted the choice, and it is not surprising that the whole system got a full rewrite in PHP 5. It is now much more advanced and flexible and should please just about everyone.

Warning

If you have used OOP in PHP 4, I strongly recommend you read this entire chapter from start to finish—OOP has been massively redesigned in PHP 5 and is much more functional and feature-rich now.

Conceptual Overview

OOP was designed to allow programmers to more elegantly model their programs upon real-world scenarios. It allows programmers to define things (objects) in their world (program), set a few basic properties, then ask them to do things. Consider an object of type Dog—there are many dogs in the world, but only one animal "dog." As such, we could have a blueprint for dogs, from which all dogs are made. While dogs have different breeds that vary a great deal, at the end of the day they all have four legs, a wet nose, and a dislike of cats and squirrels.

So, we have our dog blueprint, from which we might create a Poodle breed, a Chihuahua breed, and an Alsatian breed. Each of these is also a blueprint, but they are all based upon the Dog blueprint. From our Poodle breed, we can then create a Poodle, which we will call Poppy. Poppy is an actual dog, based upon the Poodle breed, and therefore also based upon ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.