PHP OOP - Constructor

In PHP (Object-Oriented Programming), a constructor is a special method within a class that is automatically called when an object of that class is created. It's typically used to initialize properties or run setup code.

Syntax:

class ClassName { public function __construct() { // Initialization code } }

Example:

<?php class Car { public $brand; public $color; public function __construct($brand, $color) { $this->brand = $brand; $this->color = $color; } public function displayInfo() { echo "This car is a " . $this->color . " " . $this->brand . "."; } } $myCar = new Car("Toyota", "Red"); $myCar->displayInfo(); // Output: This car is a Red Toyota. ?>

Key Points:

  • The constructor method name is __construct().

  • It can accept parameters to initialize class properties.

  • It's automatically executed when an object is instantiated.