Chapter 7. Classes and Objects
Introduction
At first, PHP wasn’t an object-oriented (OO) language. As it evolved, more and more object-oriented features appeared. First, you could define classes, but there were no constructors. Then, constructors appeared, but there were no destructors. Slowly but surely, as more people began to push the limits of PHP’s syntax, additional features were added to satisfy the demand.
However, if you’re the type of person who wishes PHP to be a true OO language, you’ll probably be disappointed. At its heart, PHP is a procedural language. It isn’t Java. But, if you’re the type of person who wants to use some OO features in your code, PHP is probably right for you.
A class is a package containing two things: data and methods to access and modify that data. The data portion consists of variables; they’re known as properties. The other part of a class is a set of functions that can alter a class’ properties; they’re called methods.
When we define a class, we don’t define an object that can be accessed and manipulated. Instead, we define a template for an object. From this blueprint, we create malleable objects through a process known as instantiation . A program can have multiple objects of the same class, just as a person can have more than one book or many pieces of fruit.
Classes also live in a defined
hierarchy.
At the top of the chain, there is a generic class. In PHP, this class
is named stdClass
, for “standard class.” Each class down the line ...
Get PHP Cookbook 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.