Adding Object Methods
If all you could do with an object was store and retrieve properties, it would still be useful, but the real power comes when you start adding methods. Methods can be as simple as "getter" and "setter" methods, which set and retrieve propertiesremember, it's bad form to access them directly from within the applicationor much more complex. Listing 7 shows the getter and setter methods for the object, as well as two new methods that create a new event and save changes to an existing event.
Listing 7Adding Object Methods (objects.inc)
<?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->set_eventid($this_eventid); $this->set_month($event["eventMonth"]); $this->set_day($event["eventDay"]); $this->set_year($event["eventYear"]); $this->set_title($event["eventTitle"]); $this->set_description($event["eventDesc"]); } // Free resources. mysql_free_result ( $results ); } function set_eventid($this_eventid){ $this->month = $this_eventid; } function set_month($this_month){ $this->month = $this_month; } function set_day($this_day){ $this->day = $this_day; } function set_year($this_year){ $this->year = $this_year; } function set_title($this_title){ $this->title = $this_title; } function set_description($this_desc){ $this->description = $this_desc; } function get_eventid(){ return $this->eventid; } function get_month(){ return $this->month; } function get_day(){ return $this->day; } function get_year(){ return $this->year; } function get_title(){ return $this->title; } function get_description(){ return $this->description; } function save_event($eventid, $month, $day, $year, $title, $description){ $querytext = "update events set eventmonth=$month, eventday=$day, eventyear=$year, ". "eventTitle='$title', eventDesc='$description' where eventid=$eventid" $results = mysql_db_query("mysql", $querytext); if ($results > 0){ echo("Record updated."); } } function create_event($month, $day, $year, $title, $description){ $querytext = "insert into events (eventmonth, eventday, eventyear, eventTitle, eventDesc) ". "values ($month, $day, $year, '$title', '$description')" mysql_db_query ( "mysql", $querytext) || die ("Cannot insert record."); } } ?>
Notice that there's nothing special about these functions, but including them in the class definition makes them methods.
By including the save_event() and create_event() methods, we can greatly simplify code on pages such as the Event Information Form.