Classes are defined similar to many other Object oriented languages.
The basic syntax is:
<?php
class theClass
{
// member declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
//this is how you create an instance of theClass
$a = new theClass();
//this is how you invoke a method on the instance
$a->displayVar();
//this is how you can access a variable in the class
echo " the variable value is $a->$var;
?>
The follwing shows you how to create a subclass of another class:
<?php
class ExtendClass extends theClass
{
// Redefine the parent method
function displayVar()
{
echo "Extending class\n";
//this calls the parent's method
parent::displayVar();
}
}
$extended = new ExtendClass();
$extended->displayVar();
?>
Constructor is created with the special name __construct and the destructor with __destruct. The following shows an example:
<?php
class Animal {
function __construct() {
print "I am an Animal\n";
}
}
class Dog extends Animal {
function __construct() {
parent::__construct();
print "and am a dog\n";
}
}
$a = new Animal();
$fido = new Dog();
?>
Here is an example with a destructor:
<?php
class theClass {
function __construct() {
print "In constructor\n";
$this->name = "theClass";
}
function __destruct() {
print "Destroying " . $this->name . "\n";
}
}
$obj = new theClass();
?>