Hello Readers, today we discussed about PHP Magic function Construct and Destruct.
The most frequent of PHP's magic approach is __construct() method and __destruct(). When you've been following along with the Building Cribbb series I'm sure you are well aware of this method already.
The __construct() method is automatically called when the target will be created. This kind of means you can utilize parameters and dependancies to set up the target.
Intended for the object is ruined the __destruct() method is fired. Again, as with the __construct() method, this is not something you have to trigger as PHP will care of it for you.
The destruct method will allow you to cleanup anything that really should not around once the object has been ruined. For example this might be a connection to an exterior service or database and session.
For example:
<?php
class Welcome {
public $name;
public $address;
public function __construct($name, $address){
$this->name = $name;
$this->address = $address;
}
public function name() {
return $this->name;
}
public function address() {
return $this->address;
}
public function destroy(){
echo "Session has been destroyed";
}
public function __destruct(){
$this->destroy();
}
}
$Welcome = new Welcome('Nitish Rawat', 'Dehradun');
echo $Welcome->name().' '.$Welcome->address();
?>
0 Comment(s)