What is the __construct() function in OOP PHP?

What is OOP?

Object Oriented Programming (OOP) is a programming concept that makes use of classes, objects, methods, and attributes, together with other provisions of the concept, to write program codes that reduce repetition.

Objects in OOP are abstractions of real-life items. So, a class is a larger set of similar objects with attributes or properties, and actions called methods, which these objects can perform together.

Although each object can have its own properties and methods that are unique to them, how do they get the properties of their base class?

How to initialize the properties of an object

You can basically do this in two ways.

One option is to provide the object properties after you create the object from the base class, just like in the code below.

<?php
//class definition
class car{
public $name;
public $color;
function set_name($name,$color){
$this->name = $name;
$this->color = $color;
}
function get_name(){
return $this->name;
}
function get_color(){
return $this->color;
}
}
//now let's create the object
$toyota = new car();
$toyota->set_name('Camry','Black');
$carName = $toyota -> get_name();
$carColor = $toyota -> get_color();
echo ' I have a '.$carColor.' toyota '.$carName;
?>

We call the set_name function to manually set the attributes.

However, a large chunk of code can be reduced if we use the second method of initializing the properties. You can use the __construct() function to set your object properties. Let’s see this method below.

How to use the __construct() function

This function allows you to create a constructor, which lets you initialize an object’s properties at the same time as the object’s creation.

Syntax

public function __construct(arg1,arg2,...argn){
    //code
}

By creating this constructor function with the __construct keyword, PHP will automatically call this function whenever you create an object from the class.

Note: The __construct function always begins with two underscores (__).

Let’s rewrite our code above using a constructor.

Code

<?php
class car{
public $carName;
public $carColor;
//now using the __construct keyword to create the construct function.
public function __construct($carName, $carColor){
$this->name = $carName;
$this->color = $carColor;
}
function get_CarName(){
return $this->name;
}
function get_CarColor(){
return $this->color;
}
}
$toyota = new car('Camry','Black');
echo 'This is a '. $toyota->get_CarColor().' ';
echo $toyota -> get_CarName().' Car';

From the sample code above, we can see that using a constructor prevents us from calling the set_name() method, which reduces the amount of code.

Free Resources