Chapter 6. Objects

In this chapter you’ll learn how to define, create, and use objects in PHP. Object-oriented programming (OOP) opens the door to cleaner designs, easier maintenance, and greater code reuse. OOP has proven so valuable that few today would dare to introduce a language that wasn’t object-oriented. PHP supports many useful features of OOP, and this chapter shows you how to use them, covering basic OOP concepts as well as advanced topics such as introspection and serialization.

Objects

Object-oriented programming acknowledges the fundamental connection between data and the code that works on it, and lets you design and implement programs around that connection. For example, a bulletin-board system usually keeps track of many users. In a procedural programming language, each user is represented by a data structure, and there would probably be a set of functions that work with those data structures (to create the new users, get their information, etc.). In an OOP language, each user is represented by an object—a data structure with attached code. The data and the code are still there, but they’re treated as an inseparable unit. The object, as a union of code and data, is the modular unit for application development and code reuse.

In this hypothetical bulletin-board design, objects can represent not just users but also messages and threads. A user object has a username and password for that user, and code to identify all the messages by that author. A message object ...

Get Programming PHP, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.