Specifications
Structure of a Class
A minimal class definition looks as follows:
class classname
{
}
In order to be useful, our classes need attributes and operations. We create attributes by declar-
ing variables within a class definition using the keyword var. The following code creates a
class called classname with two attributes, $attribute1 and $attribute2.
class classname
{
var $attribute1;
var $attribute2;
}
We create operations by declaring functions within the class definition. The following code
will create a class named classname with two operations that do nothing. The operation
operation1() takes no parameters and operation2() takes two parameters.
class classname
{
function operation1()
{
}
function operation2($param1, $param2)
{
}
}
Constructors
Most classes will have a special type of operation called a constructor. A constructor is called
when an object is created, and it also normally performs useful initialization tasks such as set-
ting attributes to sensible starting values or creating other objects needed by this object.
A constructor is declared in the same way as other operations, but has the same name as the
class. Though we can manually call the constructor, its main purpose is to be called automati-
cally when an object is created. The following code declares a class with a constructor:
class classname
{
function classname($param)
{
echo “Constructor called with parameter $param <br>”;
}
}
Object-Oriented PHP
C
HAPTER 6
6
OBJECT-ORIENTED
PHP
151
08 7842 CH06 3/6/01 3:34 PM Page 151