Advertisement

Google Ad Slot: content-top

PHP OOP - Constructor

~1 min read · PHP
On this page

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:


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:

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 "
"; echo "Color:" . $car->get_color(); ?>
Try it yourself