PHP Constructors and Destructors
A constructor is a special method that runs when an object is created. A destructor is a special method that runs when an object is removed.
A constructor runs at creation
The Born line is printed inside __construct. It appears with no method call after the new line.
<?php
class Dog {
public $name = "";
public function __construct($name) {
$this->name = $name;
echo "Born: " . $this->name . "\n";
}
}
$dog = new Dog("Rex");Two objects, two births
Each new line runs __construct for its own object. The Born lines keep the order of the new lines.
<?php
class Dog {
public $name = "";
public function __construct($name) {
$this->name = $name;
echo "Born: " . $this->name . "\n";
}
}
$first = new Dog("Rex");
$second = new Dog("Bella");unset runs the destructor
unset drops the variable and removes its object. The Gone line prints before the line written after unset.
<?php
class Dog {
public $name = "";
public function __construct($name) {
$this->name = $name;
}
public function __destruct() {
echo "Gone: " . $this->name . "\n";
}
}
$dog = new Dog("Rex");
unset($dog);
echo "After unset\n";Example
<?php
class Car {
public $year = 0;
public function __construct($year) {
$this->year = $year;
echo "Born: " . $this->year . "\n";
}
public function park() {
echo "Parked\n";
}
public function __destruct() {
echo "Gone: " . $this->year . "\n";
}
}
$car = new Car(2020);
$car->park();
unset($car);Key points
- The name __construct marks the constructor method.
- The values in the new line reach __construct as its parameters.
- __construct runs once for each object at its creation.
- The name __destruct marks the destructor method.
- A destructor runs when its object is removed.
In this example, __construct stores the year and prints the Born line. The park method prints its line next. unset then removes the car, and __destruct prints the Gone line.
Note
An object still alive at the end of a program is removed when the program ends.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
When does __construct run?