Chapter 7. Classes and Objects

Introduction

Early versions of PHP were strictly procedural: you could define functions, but not objects. PHP 3 introduced an extremely rudimentary form of objects, written as a late-night hack. Back in 1997, nobody expected the explosion in the number of PHP programmers, or that people would write large-scale programs in PHP. Therefore, these limitations weren’t considered a problem.

Over the years, PHP gained additional object-oriented (OO) features; however, the development team never redesigned the core OO code to gracefully handle objects and classes. As a result, although PHP 4 improved overall performance, writing complex OO programs with it was still difficult, if not nearly impossible.

PHP 5 fixed these problems by using Zend Engine 2 (ZE2). ZE2 enables PHP to include more advanced object-oriented features, while still providing a high degree of backward compatibility to the millions of PHP scripts already written. Later versions of PHP 5 further enhanced PHP’s OO toolkit. Today, it’s capable of allowing developers to write fully featured OO applications.

If you don’t have experience with object-oriented programming, then you’re in for a bit of a surprise. Although some features allow you to do things more easily, many features actually restrict what you can do.

Even though it seems counterintuitive, these limitations actually help you quickly write safe code because they promote code reuse and data encapsulation. These key OO programming techniques ...

Get PHP Cookbook, 3rd Edition 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.