HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP OOP - Constructor

In PHP, a constructor is a special method within a class that is automatically called when an object of that class is instantiated (i.e., created). Constructors are typically used to initialize object properties or perform any setup tasks necessary for the object to function correctly.

Here's an example of a constructor in PHP:


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

If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

Notice that the construct function starts with two underscores (__)!

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

Example

<!DOCTYPE html>
class Car {
    // Properties
    public $brand;
    public $model;
    
    // Constructor
    public function __construct($brand, $model) {
        $this->brand = $brand;
        $this->model = $model;
        echo "A new {$this->brand} {$this->model} has been created.";
    }
    
    // Methods
    public function start() {
        echo "The {$this->brand} {$this->model} is starting.";
    }
    
    public function stop() {
        echo "The {$this->brand} {$this->model} is stopping.";
    }
}

// Creating objects using constructor
$car1 = new Car("Toyota", "Camry");
$car2 = new Car("Ford", "Mustang");

</html>
You can click on above box to edit the code and run again.

Output