Classes and objects are powerful OOP concepts - and PHP4 supportsthem too. This article explains some basic OO entities (including classes,constructors and extensibility) with examples of a table builder and aguestbook.
Let's take a look at an example which illustrates how useful classes can actually be. This next class definition allows you to specify the number of rows and columns you would like, and then creates an HTML table for you on the basis of your selections.
// set the rows and columns
function setGrid($rows, $columns)
$this->rows = $rows;
$this->columns = $columns;
// set the colours and fonts
function setInterface($bcolor, $fcolor, $font)
$this->bcolor = $bcolor;
$this->fcolor = $fcolor;
$this->font = $font;
// draw the table
echo "<table border=1 bgcolor=" . $this->bcolor . ">";
for ($x=1; $x<=$this->rows;$x++)
for ($y=1; $y<=$this->columns;$y++)
echo "<td><font face=\"" . $this->font . "\" color=" . $this->fcolor .
">" . $x . ", " . $y . "</font></td>";
If you take a close look, you'll see that this class contains
three functions - one to set the number of rows and columns, one to decide the foreground and background colours and the font, and one to actually draw the table. Note the frequent usage of the $this keyword to reference local variables within the class.
Now, to use this, all you need to do is include this class definition (which you could save to a separate file named "tables.inc") within your PHP script.
// this is a PHP page which will contain many tables
// include the class definition
Here is the first table.
// first table
$alpha = new Table;
$alpha->setInterface("green", "white", "Arial");
And here's the second.
// second table
$beta = new Table;
$beta->setInterface("blue", "white", "Arial Black");
Third and fourth go together.
// third table
$gamma = new Table;
$gamma->setInterface("black", "white", "Verdana");
// fourth table
$omega = new Table;
$omega->setInterface("white", "black", "Trebuchet MS");