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.
Two of the best things about OOP are extensibility and inheritance. Very simply, this means that you can create a new class based on an existing class, add new features (read properties and methods) to it, and then create objects based on this new class. These objects will contain all the features of the original parent class, together with the new features of the child class.
As an illustration, consider the following evenBetterTable class, which adds support for cell spacing and borders.
<?
class Table
{
// constructor
function Table()
{
$this->rows = 4;
$this->columns = 5;
$this->bcolor = "black";
$this->fcolor = "white";
$this->font = "Times New Roman";
}
// 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 cellspacing=" . $this->spacing . " border=" . $this->bsize .
" 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>";
}
}
class evenBetterTable extends Table
{
// set cell spacing
function setSpacing($space)
{
$this->spacing = $space;
}
// set borders
function setBorder($size)
{
$this->bsize = $size;
}
}
?>
The "extends" keyword is used to extend a parent class to a
child class. All the functions and variables of the parent class immediately become available to the child class.
And here's how you could use it:
<?
// this is a PHP page which demonstrates extensibility and inheritance
// include the class definition
include("tables.inc");
?>
<html>
<head>
<basefont face=Arial>
</head>
<body>
<?
// first table
$alpha = new evenBetterTable;
$alpha->setGrid(4,4);
$alpha->setInterface("yellow", "black", "Arial Black");
$alpha->setSpacing(10);
$alpha->setBorder(2);
$alpha->drawTable();
?>
</body>
</html>