Chapter 6. Objects

In this chapter we will look at object-oriented programming (OOP) and focus on the best parts of it as embodied in PHP. OOP has been around for many years and is certainly a very mature programming approach in the IT world. However, it is just recently (in the last five to seven years), coming into prominence in the web side of programming. This is a good thing, too, as it makes web programming that much more robust.

Classes, objects, polymorphism, encapsulation, inheritance, methods, and properties—these are buzz words of OOP that are usually thrown around without much care. Let’s look at the definitions of these terms and then look at a sample collection of classes and see how they can work in concert.

Classes

Classes are the definition or template of the code that is to be activated in an object. You will see and edit this code, but when it is executed it will run as an object. The class is copied into existence each time it is used in your code.

Objects

An object is the copied and active form of a class. You may have heard of the term instantiation—this is just a big word for making a copy of an object in memory and giving it a unique name. When instantiating a class into an object in PHP, the new keyword is required.

Methods

A method is merely a function written within the confines of a class. In PHP, we use the word function to refer to class writing instead of method.

Properties

Properties are variables that also reside within the confines of a class.

Polymorphism ...

Get PHP: The Good Parts 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.