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.
<?
class Table
{
// 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
function drawTable()
{
echo "<table border=1 bgcolor=" . $this->bcolor . ">";
for ($x=1; $x<=$this->rows;$x++)
{
echo "<tr>";
for ($y=1; $y<=$this->columns;$y++)
{
echo "<td><font face=\"" . $this->font . "\" color=" . $this->fcolor .
">" . $x . ", " . $y . "</font></td>";
}
echo "</tr>";
}
echo "</table>";
}
}
?>
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
include("tables.inc");
?>
<html>
<head>
<basefont face=Arial>
</head>
<body>
Here is the first table.
<?
// first table
$alpha = new Table;
$alpha->setGrid(4,4);
$alpha->setInterface("green", "white", "Arial");
$alpha->drawTable();
?>
<p>
And here's the second.
<?
// second table
$beta = new Table;
$beta->setGrid(1,9);
$beta->setInterface("blue", "white", "Arial Black");
$beta->drawTable();
?>
<p>
Third and fourth go together.
<?
// third table
$gamma = new Table;
$gamma->setGrid(2,4);
$gamma->setInterface("black", "white", "Verdana");
$gamma->drawTable();
// fourth table
$omega = new Table;
$omega->setGrid(4,2);
$omega->setInterface("white", "black", "Trebuchet MS");
$omega->drawTable();
?>
</body>
</html>