PHP Objects
In much the same way that functions represent a huge increase in
programming power over the early days of computing, where sometimes the
best program navigation available was a very basic GOTO
or GOSUB
statement, object-oriented programming (OOP) takes the use of functions to
a whole new level.
Once you get the hang of condensing reusable bits of code into functions, it’s not that great a leap to consider bundling the functions and their data into objects.
Let’s consider a social networking site that has many parts. One handles all user functions: code to enable new users to sign up and to enable existing users to modify their details. In standard PHP, you might create a few functions to handle this and embed some calls to the MySQL database to keep track of all the users.
Imagine how much easier it would be, though, to create an object to
represent the current user. To do this you could create a class, perhaps
called User
, which would contain all
the code required for handling users and all the variables needed for
manipulating the data within the class. Then, whenever you needed to
manipulate a user’s data, you could simply create a new object with the
User
class.
You could treat this new object as if it were the actual user. For example, you could pass the object a name, password, and email address; ask it whether such a user already exists; and, if not, have it create a new user with those attributes. You could even have an instant messaging object, or one for managing ...
Get Learning PHP, MySQL, JavaScript, and CSS, 2nd 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.