Chapter 6. Data and Logic Together: Working with Objects
The basics of data and logic that you’ve seen so far are enough to get lots of things done in PHP. An additional concept—object-oriented programming, which combines data with the logic that operates on it—helps to organize your code. In particular, objects are great for making reusable bundles of code, so being familiar with how they work will make it easier to use lots of existing PHP add-ons and libraries.
In the programming world, an object is a structure that combines data about a thing (such as the ingredients in an entrée) with actions on that thing (such as determining if a certain ingredient is in the entrée). Using objects in a program provides an organizational structure for grouping related variables and functions together.
Here are some basic terms to know when working with objects:
- Class
- A template or recipe that describes the variables and functions for a
kind of object. For example, an
Entree
class would contain variables that hold its name and ingredients. The functions in anEntree
class would be for things such as cooking the entrée, serving it, and determining whether a particular ingredient is in it. - Method
- A function defined in a class.
- Property
- A variable defined in a class.
- Instance
- An individual usage of a class. If you are serving three entrées for
dinner in your program, you would create three instances of the
Entree
class. While each of these instances is based on the same class, they differ ...
Get Learning PHP 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.