PHP OOP - Destructor

A destructor is a special method in a class that is automatically called when an object is destroyed or goes out of scope


In PHP, destructors are defined using the __destruct() method.


 Syntax of a Destructor


class ClassName {
  public function __destruct() {
    // Code to be executed when the object is destroyed
  }
}



The example below has a __construct() function that is automatically called when you create an object from a class, and a __destruct() function that is automatically called at the end of the script:

<?php
class Car {
public $brand;
public $color;
function __construct($brand) {
$this->brand = $brand;
}
function __destruct() {
echo "The car brand is {$this->brand}.";
}
}
$car = new Car("Honda");
?>

Try it yourself

Another example:

Example
<?php
class Car {
public $brand;
public $color;
function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
function __destruct() {
echo "The car brand is {$this->brand} and the color is {$this->color}.";
}
}
$car = new Car("Honda", "Blue");
?>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.