In PHP, a constructor is a special function that allows you to automatically initialize an object's properties when the object is created. The constructor method is defined using __construct()
.
When you define a __construct()
method within a class, PHP will automatically invoke this method as soon as you create a new instance of that class. This eliminates the need to manually call other methods, like set_name()
, for initializing properties, thus making your code more efficient and concise.
The constructor method's name starts with two underscores (__)
.
Example:
<?php
class Animal {
public $name;
public $type;
// Constructor to initialize name and type
public function __construct($name, $type) {
$this->name = $name;
$this->type = $type;
}
// Method to get the name of the animal
public function get_name() {
return $this->name;
}
// Method to get the type of the animal
public function get_type() {
return $this->type;
}
}
// Create an instance of the Animal class
$lion = new Animal("Lion", "Mammal");
// Output the animal's name and type
echo "Name: " . $lion->get_name() . "\n";
echo "Type: " . $lion->get_type();
/*
Output:
Name: Lion
Type: Mammal
*/
?>
Destructor
A destructor is a special function that gets called when an object is destroyed or when the script finishes executing. If you define a __destruct()
function in your class, PHP will automatically invoke this function when the object is no longer needed or when the script finishes execution.
It's important to note that the destructor function's name begins with two underscores (__
).
In the example below, there is a __construct()
function that is automatically called when an object is created from a class, and a __destruct()
function that is automatically called when the script ends.
<?php
class Animal {
private $name;
private $species;
// Constructor with an optional species parameter having a default value
public function __construct(string $name, string $species = "Unknown") {
$this->name = $name;
$this->species = $species;
}
// Destructor to display a message when the code execution is complete
public function __destruct() {
echo "The animal is {$this->name}.";
}
}
// Create an instance of the Animal class
$lion = new Animal("Lion");
// Desctruct function will run here automatically because this is the end of the script
/*
Output:
The animal is Lion.
*/
?>