In PHP, there are special "magic methods" that are automatically called at certain points in an object's lifecycle. The most important of these are the **Constructor** and the **Destructor**.
A constructor allows you to initialize an object's properties when the object is created. It is defined using the __construct() magic method (with two underscores).
When you create an object with the new keyword, PHP automatically calls the __construct() function inside the class.
<?php
class Fruit {
public $name;
public $color;
// Constructor
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_fruit() {
return "This is a " . $this->color . " " . $this->name;
}
}
// Initialize the object with arguments
$apple = new Fruit("Apple", "Red");
echo $apple->get_fruit(); // Outputs: This is a Red Apple
?>
set_name() and set_color() calls every time you create an object.
A destructor is called when the object is destroyed or the script stops or exits. It is defined using the __destruct() magic method.
This is useful for cleaning up resources, such as closing a database connection or writing logs, just before the object is removed from memory.
<?php
class Fruit {
public $name;
function __construct($name) {
$this->name = $name;
echo "Object created: " . $this->name . "<br>";
}
// Destructor
function __destruct() {
echo "Object destroyed: " . $this->name;
}
}
$apple = new Fruit("Apple");
// Script ends here, destructor will be called automatically
?>
__. Never name your own custom functions with a double underscore prefix.