PHP Constructor

In PHP, a constructor is a special method within a class that is automatically called when an object of that class is created. learn basic classes and objects from here.

It is used to initialize the object’s properties or perform any necessary setup tasks.

To define a constructor in a PHP class, you use the __construct() method.

Here’s a real-world example:

class Car {
    public $color;
    public $brand;
    // Constructor
    public function __construct($color, $brand) {
        $this->color = $color;
        $this->brand = $brand;
        echo "A new car object has been created!";
    // Other methods...

In the above example, the Car class has a constructor defined with the __construct() method.

The constructor takes two parameters ($color and $brand) which are used to initialize the color and brand properties of the object. Within the constructor, the -> arrow operator is used to assign the parameter values to the object’s properties.

When an object of the Car class is created, the constructor is automatically called, and it sets the provided values for $color and $brand. Additionally, it echoes the message “A new car object has been created!” as specified in the constructor.

Here’s how you would create an object and invoke the constructor:

$car = new Car("Blue", "Toyota");

The code above creates a new Car object with the color “Blue” and the brand “Toyota“. As soon as the object is created, the constructor is executed, initializing the object’s properties and displaying the message.

Constructors are useful when you need to perform some initialization logic or set default values for object properties. They allow you to ensure that an object is properly initialized upon creation.