Tutorial: Writing Classes in PHP

by Brian Haase, July 2004
Part 1 :: Introduction
Part 2 :: Class Structures
Part 3 :: Using the Class
Download complete script

Requirements: PHP4, register_globals are assumed to be off.

Introduction

Some consider classes one of the hardest components of PHP to figure out, but the reality is that classes are extremely straightforward and easy to use. The trouble comes from the fact that not all programmers have worked with Object-Oriented Programming (OOP) before.

Classes are little more than a container for variables and functions affecting those variables, but they can be very useful for building small components - almost miniture programs.  The difference is that you dont need to shell out to them or anything, and they can be plugged into most scripts with ease - Just a require or include statement at the top. A class describes an 'object'. An object is a collection of smaller objects, just like in a class. Say for instance, we want to describe a simple door lock. A lock class might contain:

        variable $Bolt
        variable $Position
        
        function TurnKey( $Direction, $Distance )
        function CheckLock( )
TurnKey would accept a direction value that would in turn determine if the bolt should be locked or unlocked. Once the key is turned far enough in either direction ($Distance) the Bolt will either set or clear. The $Bolt variable shows the current state of the door lock, and $Position is used to track how far the key has been turned in any direction. Now, obviously this could all be done with regular variables and functions, and if you only need to use one lock in the code, it would probably work just fine. But what if you want more than one lock? One if you wanted more details about the lock, or even something else? Maybe you want a door in the code, too - And the lock would just be a subset of the door. Maybe you have a whole house. You might have more than one door, or you might not. But each door certainly needs a lock. You can see how complex object-related problems can get. 

By using classes, you can define an object once, and then include it in several scripts also. You'll be assured that your object will funciton the same in all of the scripts! Its good practice to write your classes in a seperate file usually, that way you only have to change it in one location. Make full use of PHP's include and require functions, they have many uses.

In the next section, I will walk you through creating a simple class.


Class Structures

For lack of a better example right now, i'm going to show you how to create a simple page object. The page object encompasses a few of the basic page necessities in building an HTML page. Now, there is a lot more you could do with this class, but i'm going to keep it simple for the time being. You guys can expand on it if want later. Okay, lets start by looking at what the basic elements of an HTML page are. First, you have the open and closing tags, <HTML> and </HTML>. Those will need to be included in the output. Also, you have the page Title, Keywords for the Metatag field, and naturally the main content, or body. Now that we know what we need, lets start building our class. 

First thing we need is the class itself: 

<?php
 class Page {

 }
?>

This is a basic class. No variables, no functions, nothing - Completely empty. All class structures look the same here with the exception of the 'Page' name. Every class/object is assigned a name for reference. You'll need to know this to create new copies of the object, so pick something straightforward and sensible. 

Next, we need to put in our variables. We need a title for the page, keywords, and a content body, like so: 
<?php
class Page {
   var $Title;
   var $Keywords;
   var $Content;  
 }
?>

Now, we could actually start using the class here. We have an object. But it isn't done - We still want to add some functions, to make it easier to work with. 

What functions do we need? Well, we need something to build the output HTML. Lets call that 'Display'. Lets create simple functions for displaying the Title and Keywords, also. Lets make a function for setting the content as well. 

The final class code is:
<?php
class Page {
   var $Title;
   var $Keywords;
   var $Content;

   function Display( ) {
     echo "<HTML>\n<HEAD>\n";
     $this->DisplayTitle( );
     $this->DisplayKeywords( );
     echo "\n</HEAD>\n<BODY>\n";
     echo $this->Content;
     echo "\n</BODY>\n</HTML>\n";
   }

   function DisplayTitle( ) {
     echo "<TITLE>" $this->Title "</TITLE>\n";
   }

   function DisplayKeywords( ) {
     echo '<META NAME="keywords" CONTENT="' $this->Keywords '">';
   }

   function SetContent$Data ) {
     $this->Content $Data;
   }
 }
?>

Now, at first glance this looks pretty simple. And you know what? It is. Its just basic PHP code wrapped into a class. Let me point a few things out before we go any farther though.

VAR -
 All variables declared in the class must be placed at the top of the class structure, and preceeded with the VAR statement. 
$THIS -
 $this is a variable that incidates the current object. That way, the object knows how to find itself while running functions contained within it. 
 For instance, $this->Keywords gets the data from the $Keywords variable in the object. You'll also notice that when using variables contained 
 within a class, you can't use the $ to reference them - But you have to use it to reference the object itself. 

Lets save this class file out before we continue. If your following along, save it out as page.class for now. You'll need it for the example coming up.  

Using the Class

Now that we have a class created, lets try using it in a normal script. 

<?php
 include "page.class";

 $Sample = new Page;

 $Content "<P>This page was generated by the Page Class example.</P>";

 $Sample->Title "Using Classes in PHP";
 $Sample->Keywords "PHP, Classes";
 $Sample->SetContent$Content );

 $Sample->Display( );

?>
Doesn't get much simpler than that, does it? We use the include statement to bring in the class from its external file. We use the 'new' statement to create a new copy of the object so we can work with it. The new copy is stored into a variable called $Sample. Then we just set some variables - The Title, Keywords and Content - And use the Display function to output it. Easy or what?

© Copyright 2003-2014 www.php-editors.com. The ultimate PHP Editor and PHP IDE site.