Home > Articles > Programming > PHP

  • Print
  • + Share This
Like this article? We recommend

Importing Classes from a Separate File

Although it's useful to modularize our code the way we have, it's best if every page that refers to events does it through Event objects. So for maintenance purposes, it's best to move the class definition into a separate file that we can call from different pages. To start, create a new file—I'll call mine objects.inc, and I'll place it in the same directory as showevent.php—and save it. Place the class definition in that file, as shown in Listing 5.

Listing 5—A Separate Class Definition File (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->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 );

  }
}
?>

Notice that the entire section is enclosed in the <?php and ?> delimiters.

To actually use the object, we need to make the class definition available from within the page. To do that, we can use the require() function, as shown in Listing 6.

Listing 6—Making the Class Definition Available (showevent.php)

<?php
  require("objects.inc");

  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 );

?>

The require() function acts as if all of the code in the objects.inc file were included in this file at that point.

Four functions enable you to include code from another file: include(), require(), include_once(), and require_once(). All four can take a local file or URL as input. The difference between the include and require functions is that include() and include_once() provide a warning only if the resource can't be retrieved; whereas require() and require_once() stop processing the page. Because we need the class definition to proceed, we're using require().

The include_once() and require_once() functions are handy in situations where multiple files may reference the same included code; if the file has already been included, it won't be included again. Because a function can't be redefined once it's declared, this restriction can help prevent errors.

  • + Share This
  • 🔖 Save To Your Account