Advertisement

Google Ad Slot: content-top

PHP OOP - Constructor


What is a Constructor in PHP?


A constructor allows you to initialize an object's properties upon creation of the object.


A constructor is a special method in a class that is automatically called when a new object of the class is created.


In PHP, constructors are defined using the __construct() method.


Syntax of a Constructor


class ClassName {
  public function __construct() {
    // Code that runs when an object is created
  }
}



We see in the example below, that using a constructor saves us from calling the set_name() method which reduces the amount of code:


<?php
class Car {
public $brand;
public $color;
// Constructor
function __construct($brand) {
$this->brand = $brand;
}

// Methods
public function get_brand() {
return $this->brand;
}
}
// Creating objects with constructor
$car = new Car("Honda");
echo $car->get_brand(); // Output: This is a Honda.
?>
Try it yourself

Another example:

<?php
class Car {
public $brand;
public $color;
// Constructor
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
// Methods
public function get_brand() {
return $this->brand;
}
public function get_color() {
return $this->color;
}
}
// Creating objects with constructor
$car = new Car("Honda","Blue");

echo "Brand:" . $car->get_brand();
echo "<br>";
echo "Color:" . $car->get_color();
?>
Try it yourself