PHP Basics, Part 3: User-Defined Functions and Objects
In the first article of this series on PHP basics, we looked at the structure of a pageincluding variables, looping, and HTML forms. In the process, we created the first part of an event information system, with a monthly calendar displayed based on the month chosen on the form. In the second article, we added a database to the site, creating the pages that add and display event information.
In this article, we look at using PHP to create user-defined functions. We'll then extend it, if you'll pardon the expression, to the idea of using PHP objects.
In order to follow along with the examples, you need a Web server that supports PHP. Many Web hosts provide PHP support, or you can download it for free at http://www.php.net. You also need access to a database. These examples use mySQL, which is available for free at http://www.mysql.com.
Why Objects?
In the previous articles, we created a simple calendar system to enable an administrator to enter information on community events using a Web-based form. That information is then stored in a database. We accomplished all of this through an application that basically started at the top and worked its way down to the bottom. This style is known as procedural programming.
In this article, we will look at a style known as object-oriented programming, or OOP. For those of you unfamiliar with the concept of OOP, it involves creating an object, such as an Event, that has properties such as the date or title; and methods, such as the capability to add itself to the database or change information about itself within the database.
In OOP, programming related to a particular object is kept within a class, which acts as a template for the object. For example, in this article we'll create the Event class, which has information on how to add to and edit existing events in the database; then create an object based on that class. The actual page doesn't have to know anything about how the information is stored; it simply calls a method, save_event(), and the object takes care of the rest. If changes ever needed to be made, say to the database structure or even to store events in some completely different way, the main application is untouched because all of the changes take place within the class from which the object is created.
Of course, there's a whole lot more to objects than that, but we'll keep it simple here.
To start, we look at creating a brand-new function.