PHP Classes
Shobhan Challa on 2002 June 08
    

IF you've been programming with PHP you may have came across OOP. The term OOP stays for Object Oriented Programming and refers to a technique in which you work with Objects in your programs. When I first started using Objects in PHP it was difficult for me to understand its concept, but, once I got it, I found them quite simple to work with

.

In this article I'll take you through the concept of Objects in PHP4 with an example I've shown earlier in my article PHP/mySQL Guestbook (http://www.phpbeginner.com/columns/shobhan/guestbook).

What are Objects?

An object is a procedure that, can be called and passed arguments to, to then do something for you. Do not confuse an object with a simple page (yes, you pass data to it as well), an object is being used only when being called, other times its "sleeping". The most common examples of objects are Classes and Functions.

In PHP a Class is nothing but a collection of functions (methods) which perform a specific task (also called Objects). Each Class can be defined (used) more times on the same page (have multiple instances). And, finally, every class has its own methods (functions) to be then called from within a page.

You can think of a class as of a group of functions. But, not quite, read on.

The difference is, within a class you can share the variables that are global for the instance of the class yet, are local for the whole rest of the code. In PHP one can create any number of instances of a class and each of it will be totally independent with its own properties.

What should I them for?

You may ask what's the use of Classes. Well, classes help you to keep your code modular or, better say, untouched. For example, you can make a class that draws a html table for you, then define it, call it, pass data to it and voila! - your table is set. If this works, export the class into its own file and keep including it whenever you need to draw a table. This way you simplify and expand the ever-repeating code. If you need to change the processing section you can edit a particular file without disturbing the other part of the code.



Guestbook Class

Every class definition starts with the keyword class, followed by class name. Remember that the class name doesn't collide with the reserved words in PHP. (use get_declared_classes() to know it for sure).

A typical class definition looks like this:


<?php


  
class   Guestbook //class definition
    
    
function Guestbook//constructor
    
$this->title "Guestbook Demo";
    }
  }


?>


To create an instance of this class , we use the keyword new and assign the object to a variable


<?php


    $Gbook 
= new Guestbook();


?>


Here we created a new object Guestbook and assigned it to the variable $Gbook. Now you can access the methods of the Guestbook class using this variable.


<?php


$Gbook
->display(); //call the display method 


?>


In the Guestbook class you may have noticed the keyword $this. The keyword can be used to access the functions or to modify the values within the class definition. It also provides a convenient way to access variables and functions local to the class.



Now enough theory, lets get put our Guestbook class to work. Before continuing remember to setup your database and table. For setting up the table go through my article PHP/mySQL Guestbook. The program below uses the same table as given in the PHP/mySQL Guestbook article.


<?php


    
//base Connection for DB
    
$dbhost="localhost";
    
$dbuser="db_user";
    
$dbpasswd="db_password";
    
$db "db_name";

    
$mysql_link mysql_connect($dbhost$dbuser$dbpasswd) OR DIE ("no connection to db server");


    
$selectresults mysql_select_db("$db"$mysql_link) OR DIE ("Cannot select database $db");

    
#....end..........connection


?>


save this as connection.inc.

Finaly, the Guestbook class:


<?php


    
/*
    Guestbook class for inserting and displaying the Guest entries
    */

    
include('connection.inc'); //Connection file for the Database

    
class Guestbook{

        function 
Guestbook() { //Constructor 
            // default settings
            
$this->title " Guestbook Demo ";
            
$this->fontface "Verdana";
            
$this->fontsize "2";
            
$this->fontcolor "#FFFFFF";
        }

        function 
show_entry_form(){ //Sign form
            
global $name$email$message;

            
?>

<form action="$PHP_SELF" method="post">
<center>
<table width="600" cellpadding="10" cellspacing="5" >

<tr>
<td width="300" align="right">
Name
</td>
<td width="300" align="left">
<input type="text" name="name" size="25" value="$name">
</td>
</tr>

<tr align="center">
<td width="300" align="right">
Email Address
</td>
<td width="300" align="left">
<input type="text" name="email" size="25" value="$email">
</td>
</tr>

<tr>
<td align="right" width="300">
Comments
</td>
<td align="left" width="300">
<textarea name="message" cols="25" rows="3" wrap="virtual">
$message
</textarea>
</td>
</tr>

<tr>
<td align="center" colspan=2 width="600">
<input type="submit" value="Sign">
</td>
</tr>

</table>
</center>
</form>

<?php
        
}



        
//This function inserts the info to the DB 
        
function add_entry() {
            global 
$name$email$message;
    
            
$query  "
                INSERT INTO guest_messages (guest_name, guest_email, guest_time, guest_message)
                VALUES('$name', '$email', NULL, '$message')
                "

            
$result mysql_query ($query);
        }


        
//This function list the last 20 entries from the DB
        
function show_entries() {
            echo 
"<hr width=100%>";

            
$query  "SELECT * FROM guest_messages ORDER BY guest_time DESC Limit 20";
            
$result mysql_query($query);

            echo 
"<table border=1>n";
            echo 
"<th>Name</th><th>Email</th><th>Comments</td>";

            while (
$row mysql_fetch_array($result)){
                echo 
"<tr>n";

                echo 
"<td><font face="$this->fontface" size=$this->fontsize>";
                echo 
$row['guest_name'];
                echo 
"</font></td>";

                echo 
"<td><font face="$this->fontface" size=$this->fontsize>";
                echo 
$row['guest_email'];
                echo 
"</font></td>";

                echo 
"<td><font face="$this->fontface" size=$this->fontsize>";
                echo 
$row['guest_message'];
                echo 
"</font></td>";

                echo 
"</tr>n";
            }
            echo 
"</table>";
        }


        
// display page
        
function display() {
            
$this->show_entry_form();
            
$this->show_entries();
        }
    }


?>


The Guestbook class contains four member functions: show_entry_form(), add_entry(), show_entries() and display(). Here the use of display() is to call the show_entry_form() and show_entries(). Save the above as guestbook.inc.



Now the main PHP file which uses the class:


<?php


    
/*
    GuestBook Demo using Class
    Author: Shobhan Challa
    Date : 20-05-2002
    */

    
include("guestbook.inc"); //include the class file

    
$Gbook = new Guestbook(); //Instantiate the Guest book


    
if($name && $email) {
        
$Gbook->add_entry();
    }

    
$Gbook->display(); //Display the entries

?>


Save this as guestbook.php. The example uses only one class, but a class can also extend another class . The two good things about OOP are inheritence and extensibility. You can create a new class based on another class adding so new features to it. A child class created on base of the parent class will acquire parent class's functionality and extend it by new ones. Great for reusing your code.

To give you an example, we can extend our Guestbook class like this:


<?php
    
class  AnotherGuestbook extends Guestbook {
        function 
AnotherGuestbook{
            
// code here
        
}
    }

?>


Here the extends keyword literally extends the parent Guestbook class to a child AnotherGuestbook class. All the functions and variables of the parent class can now be accessed by AnotherGuestbook.

Hopefully, I've confused you well enough covering the basics of the Classes in PHP.
Get this code, work on it, extend it, modify it... and, remember where you got it, so you can always start from the beginning till you get handy with Object Oriented Programming in PHP!

The example in this article have been tested on Linux with Apache and PHP 4.0.6.

Shobhan Challa
Tentatively planning to Open Soon! (no dates ...) // Doing heavy development now...