The __construct Function in PHP
A constructor lets you set up an object\’s properties when you first create it.
If you make a __construct() function, PHP will automatically call it whenever a class is used to make an object.
Notice that the construct function begins with two underscores (__)!
In the example below, we can see that using a constructor saves us from having to call the set name() method, which makes less code:
Example
<!DOCTYPE html>
<html>
<body><?php
class Student {
public $name;
public $rollno;function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}$ram = new Student(\”Ram\”);
echo $ram->get_name();
?></body>
</html>
Output
Ram
The __destruct Function in PHP
When an object is destroyed or when a script is stopped or closed, the destructor is called.
If you make a __destruct() function, PHP will automatically call it when the script is done.
Notice that the destruct function begins with two underscores (__)!
In the example below, the __construct() function is called automatically when an object is created from a class, and the __destruct() function is called automatically when the script ends:
Example
<!DOCTYPE html>
<html>
<body><?php
class Student {
public $name;
public $rollno;function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo \”The Student name is {$this->name}.\”;
}
}$ram = new Student(\”Ram\”);
?></body>
</html>
Output
The Student name is Ram.