PHP5 Class Basics, Part 1
(Page 2 out of 3)As I said earlier, a class can also have its own variables, called properties. See the example below:
public $name;
function drive() {
echo 'Vrooooom... ' . $this->name;
}
}
We have added two things in the example below. First of all, we have added a new property by adding the line: "public $name". This gives our class a new public property called $name. The second thing we've done is change the drive() method, as it now prints the value of the $name property. As you can see we use $this->name to refer to the $name property.
The $this variable refers to the current instance, and must be used when you want to access a property or method from within the class.
The example below demonstrates the use of the $name property and the $this variable:
Class MyCar {
public $name;
function drive() {
echo 'Vrooooom... ' . $this->name;
}
}
// Instance 1
$porsche = new MyCar();
$porsche->name = 'Porsche';
$porsche->drive();
echo '';
// Instance 2
$bmw = new MyCar();
$bmw->name = 'BMW';
$bmw->drive();
echo '';
// Instance 3
$volvo = new MyCar();
$volvo->name = 'Volvo';
$volvo->drive();
echo '';
?>
If you run the above example you'll see that the value of the name property is different for each object, as it should.
Constructor/Destructor
Classes come with two special methods called a constructor and a destructor. A constructor method will be called when a new instance of the class is created, and is commonly used to set the initial status of the class. Typical uses of the constructor include setting up a database connection or setting some default properties. The example below demonstrates the use of a constructor:
Class MyCar {
public $name;
function __construct($name) {
$this->name = $name;
}
function drive() {
echo 'Vrooooom... ' . $this->name;
}
}
$porsche = new MyCar('Porsche');
$porsche->drive();
?>
In the example above we used the constructor to set the $name property of our class. As you can see we passed an argument when creating a new instance of the class.
The destructor is used to execute code when an object gets removed, by unsetting the object with the unset() function, or when the script ends. Usually the destructor is used to perform clean up tasks, such as closing database connections, saving data to the hard disk, etc. The example below demonstrates the destructor:
Class MyCar {
public $name;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo '*crash* this car has been destroyed';
}
function drive() {
echo 'Vrooooom... ' . $this->name;
}
}
// Instance 1
$porsche = new MyCar('Porsche');
$porsche->drive();
echo '';
unset($porsche);
?>
September 1st, 2006 at 9:22 pm
PHPit.net: PHP5 Class Basics, Part 1…
…