PHP Oops Constructor - PHP Constructors and Destructors



PHP Constructor

  • A PHP constructor is a special type of function that is automatically called when an object is created.
  • It is used to initialize variables and set the initial state of an object.
  • Constructors can also be used to perform operations on the object after it has been created.
php-constructor

Sample Code

<?php
class Car {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  function get_name() {
    return $this->name;
  }
  function get_color() {
    return $this->color;
  }
}
$audi = new Car("Audi", "white");
echo $audi->get_name();
echo "<br>";
echo $audi->get_color();
?>

Output

Audi
white

Related Searches to PHP Oops Constructor - PHP Constructors and Destructors