Adding Class Functionality
Now that we have the basic idea, let's start retrieving actual information about a real event. The easiest way to do this is to simply add the data retrieval to the constructor, so that when the object is created, it's populated with real information instead of our arbitrary placeholders, as shown in Listing 4.
Listing 4Adding Data Retrieval to the Object
<?php class Event { function Event($this_eventid){ // Connect to database. $connection = mysql_connect ( "localhost", "myusername", "mypassword" ) || die ( "Error connecting to database!" ); // Get each entry $results = mysql_db_query ( "mysql", "SELECT * from events where eventid=$this_eventid"); while ( $event = mysql_fetch_array ( $results ) ) { $this->eventid = $this_eventid; $this->month = $event["eventMonth"]; $this->day = $event["eventDay"]; $this->year = $event["eventYear"]; $this->title = $event["eventTitle"]; $this->description = $event["eventDesc"]; } // Free resources. mysql_free_result ( $results ); } } import_request_variables('pgc', ''); $this_event = new Event($eventid); printf ( "<h2>%s</h2>", $this_event->title ); printf ( "<h3>Date: %s/%s/%s</h3>", $this_event->month, $this_event->day, $this_event->year ); printf ( "<p>%s</p>", $this_event->description ); printf ( "<a href='saveevent.php?editid=%s'>Edit this event</a>", $eventid ); ?>
Notice that there's nothing special about the code that retrieves the object information, except that instead of setting traditional values, we're setting object properties. When $this_event is created, the information is pulled from the database. (Note that because there should be only one event with a particular eventid, the while loop should execute a maximum of one time.)
Notice also that the code to display the data hasn't changed one bit. The page doesn't care how the object's properties were instantiated, just that they were. The best part of this is that we can completely change the way in which we store object information, and we won't have to touch the main page program.
We can get an even greater advantage from this capability by separating the class definition itself out into a separate file that can be called from multiple pages.