Search⌘ K

The construct() Magic Method

Explore how to use the __construct magic method in PHP to initialize object properties when creating objects. Learn to handle default values and avoid errors if no argument is passed, ensuring flexible and safe object instantiation.

Constructor method

We use the __construct() method in order to do something as soon as we create an object out of a class. A method of this kind is called a constructor.

Note: The names of magic methods always start with two underscores. The __construct() magic method is no exception.

Usually, we use the constructor to set a value to a property. In our simple example, we should set the value of the $model property as soon as we create the object, so we add a constructor inside the class that sets the value of the ...