Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
oop
constructor
communitycreator

How to create the class constructor in PHP

Saad Akbar

Overview

In OOP, when a constructor is declared, it initializes the properties of an object.

The __construct function

In PHP, we have the __construct function for such purposes.

Note: We use the double underscore __ before construct.

Once we have the __construct() function in a class, the subsequent object of that class will initiate the variables and the functions inside it. Therefore, we don’t have to manually create/initialize them.

Code

For instance, in the provided example, we don't have to call the specific functions, set_brand() and set_name() to initialize the brand and name variables. This is because it's been done by the __construct() function that saves up our code space and reduces the manual efforts/steps we have to perform for such purposes.

<?php
class Car {
  public $brand;
  public $name;

  function __construct($brand, $name) {
    $this->brand = $brand;
    $this->name = $name;
  }

  function get_brand() {
    return $this->brand;
  }

  function get_name() {
    return $this->name;
  }
}

$car1 = new Car("Honda", "Civic");
echo $car1->get_brand();
echo " ";
echo $car1->get_name();
?>
The __construct function in PHP

Explanation

  • Lines 1-18: We create a class named Car with a brand and a name. Then, we create the __construct function and pass the brand and name as its parameters. This function initializes the brand and name with the input that the user provides when it creates a class object. Furthermore, we create a get_brand() and get_name() function to return the brand and name that is assigned to the class object.
  • Lines 20-23: We create a Car object car1 and pass it the brand and name in the braces. After this, we simply print the brand and name through the get functions.

RELATED TAGS

php
oop
constructor
communitycreator
RELATED COURSES

View all Courses

Keep Exploring