Skip to main content

The __construct() Function

A constructor is a special method named __construct(). PHP runs it automatically every time you create a new object from the class with the new keyword.

It can take arguments, which you supply at the moment the object is created, as in $apple = new Fruit("Apple", "Red");. That way, each object is set up with its own values right away and you write less code.

Watch the name: it begins with two underscores (__).

The next example relies on __construct() to fill in the properties. Since PHP calls it for us, there is no need for a separate call to a set_details() method, and the code gets shorter:

Constructor Example

Set an object's properties at creation time with __construct():

Prompt
Write a PHP script that defines a Fruit class with a __construct() function that accepts $name and $color, and a get_details() method. Create two Fruit objects and display their details.
Output: PHP script

Example Explained

The Fruit class declares two properties, $name and $color.

Whenever a new Fruit object appears, __construct() stores the values it received in those properties.

The job of get_details() is to print the fruit's name and color.

The line that creates $apple passes the values "Apple" and "Red" to the constructor, and the line that creates $banana does the same with "Banana" and "Yellow".

Finally, calling get_details() on each of the two objects displays that fruit's details.