PHP OOP Constructor

Constructors are functions used for creating newly created object instances from a class. When creating an object, the constructor function is used to set the object’s properties.

When you create an object from a class, PHP will automatically call the __construct() function you defined.

Constructor Syntax:

It is a public function that is written as __construct.

function __construct()
       {
       // initialize the object and its properties by assigning 
values
       }

Let’s start by making the example using the constructor method having $name and $colour as arguments. These arguments should be passed in when the object is created.

<?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;
  }
}

$car = new Car("Civic", "black");
echo $car->get_name();
echo "<br>";
echo $car->get_color();
?>

Note: By using the constructor function there is no need to use the set function to set the value of an argument.