Constructor in PHP: Syntax, Types, Examples

A constructor in PHP is a special method in a class that is used to initialize the object’s properties. It is also used to perform actions required to set up the object so that it can function properly.

A constructor is automatically called at runtime when you create an object (or instance) of a class using the new keyword. In PHP, it is defined using the __construct() method.

Syntax to Create Constructor in PHP


The general syntax to create constructor in a PHP class is as:

public function __construct()
{
   // Code goes here.
}

In the above syntax of constructor,

  • public – This is an access modifier that controls the visibility of the constructor. The constructor can also be declared as protected or private.
  • function __construct() – This defines the constructor method.
  • Curly braces { … } – These enclose the initialization code that runs when an instance of the class is created.

Let’s take a simple example of constructor in PHP.

Example:

<?php
class Test {
   public function __construct() {
     echo "Constructor called automatically!";
   }
}
// Create an object of class Test.
$test = new Test();
?>

Output:

Constructor called automatically!

In this example,

  • We have defined a class named Test.
  • A class is a blueprint for creating objects in PHP.
  • Then, we have defined a constructor method using __constructor(). Here, the double underscore (__) indicates that it’s a magic method in PHP.
  • The constructor is called automatically whenever an object of the class is created using the new keyword.
  • Inside the constructor, the statement “echo “Constructor called automatically!”;” prints the message on the screen when the object is created.
  • The statement $test = new Test(); creates an object of the Test class.
  • As soon as this line executes, PHP automatically calls the __construct() method of the Test class.

How This Example Works?

When you create an object of the Test class using new keyword, PHP allocates memory for the new object. After the object is created, PHP automatically calls the constructor method __construct() and executes the code inside it. In the above example, we have simply displayed a message on the screen to show that how has the constructor been executed.

Characteristics of PHP Constructors


There are the following characteristics of constructors based on the latest version of PHP. They are:

Top 10 Characteristics of constructor in PHP.

1. Automatic Invocation

  • When you instantiate a class using new keyword (for example, new Test()), PHP automatically calls its constructor method named __construct().
  • You don’t need to call the constructor yourself. The new keyword triggers it.
  • Any initialization or setup operation you place inside the __construct() method will run each time an object of the class is created.

2. Named __construct() Method

  • In PHP 4, a constructor was created by defining a function with the same name as the class. However, this approach is now deprecated.
  • Starting from PHP 5, you can create a constructor by defining a magic method named __construct().
  • A magic method is a predefined method in PHP that begins with a double underscore (__).

3. Return Value

  • A constructor cannot return a value in PHP. Its primary purpose is to initialize objects, not to return data.
  • Unlike regular functions or methods, a constructor does not use a return statement.

4. Initialization Role

  • The main role of a constructor is to initialize the object’s properties (variables) and perform any necessary setup tasks required for the object to be in a valid state.
  • This may include setting default values, performing validations, or allocating resources such as database connections or file handles.

5. Parameter Acceptance

  • Constructors can accept parameters, allowing initial values to be passed during object creation.
  • These parameters are then used to initialize or set the object’s properties.

6. Visibility Control

You can declare a constructor with an access modifier such as public, protected, or private.

  • public: It means you can instantiate the class from anywhere — both inside or outside the class.
  • protected: If you declare a constructor as protected, you can instantiate the class within the same class or its subclasses.
  • private: If you declare a constructor as private, it prevents direct instantiation from outside the class. A private constructor is often used in singleton patterns or factory methods.

7. Typed Parameters and Default Values

  • Modern PHP allows constructor parameters to be typed. You can define parameters using scalar types such as int and string, as well as class types and union types.
  • This ensures that the correct argument types are passed during object creation.
  • You can also assign default values to parameters, providing greater flexibility.
  • In PHP 8.1 and later, union types and other advanced type features allow you for richer and more precise object initialization.
  • This means the constructor can receive strongly typed inputs, which improves code clarity and reduces runtime type errors.

8. Constructor Property Promotion

  • PHP 8.0 introduced a shorthand syntax that allows you to declare and initialize properties directly in the constructor parameter list. For example:
class Student {
    public function __construct(private string $name, public int $age = 0) {
       // Additional initialization logic
    }
}
  • This eliminates the need for separate property declarations and assignment inside the constructor.
  • Note that only __construct() method supports this promotion. Other methods can’t use it.
  • Constructor property promotion is one of the most important features in modern PHP for reducing code duplication and making classes more concise.

9. Support for readonly Properties (PHP 8.1+)

  • With PHP 8.1 and later, you can declare class properties as readonly. The assignment to readonly properties only occurs once inside the constructor. You cannot change it once assigned. For example:
class Order {
    public function __construct(public readonly int $orderId) { }
}
  • This feature is often useful for immutable objects, where a property should not change once the object has been created.

10. Only One Constructor Per Class

  • You can define only one constructor using __construct() method.
  • However, you can provide default values or overloaded behavior via parameters, but you cannot have multiple constructors distinguished by name or signature.

Types of Constructors in PHP


There are mainly two types of constructors in PHP based on whether they accept parameters:

  • Default constructor
  • Parametrized constructor

Let’s explore each in detail with syntax and examples.

Default Constructor in PHP


The constructor that does not take any parameters is called default constructor in PHP. It is automatically called when you create an object of the class. This type of constructor is mainly used to initialize default values, establish connections, or perform other setup operations when an object is created.

Syntax to Declare a Default Constructor:

class ClassName {
    public function __construct() {
      // Initialization code
    }
}

Example 1: Basic Default Constructor

<?php
class Student {
// Default constructor.
   public function __construct() {
      echo "Default constructor called!";
   }
}
// Create an object of the class Student.
$obj = new Student();
?>

Output:

Default constructor called!

In this example, we have created a class named Student. Then, we have defined a constructor using a magic method __construct(). When an object of the class is created using new keyword, PHP automatically calls the __construct() method and executes the code inside it.

Example 2: Default Constructor with Initialization

<?php
class Person {
   public $name;
   public $email;

// Create a default constructor.
   public function __construct() {
      $this->name = "Deepak";
      $this->email = "contact@scientecheasy.com";
   }
}

// Create an object of class Person.
$person = new Person();
echo "Name: " . $person->name . "\n";
echo "Email ID: ". $person->email;
?>

Output:

Name: Deepak
Email ID: contact@scientecheasy.com

Parameterized Constructor in PHP


A parameterized constructor in PHP is a constructor that accepts parameters to initialize an object’s properties with specific values at the time of object creation. It allows you to pass data to the constructor when creating an instance of the class.

Syntax to Declare a Parameterized Constructor:

class ClassName {
   public function __construct($param1, $param2, ...) {
      // Use parameters to initialize properties
   }
}

Example :

<?php
class Employee {
   public $name;
   public $position;

// Declare parameterized constructor.
   public function __construct($name, $position) {
      $this->name = $name;
      $this->position = $position;
   }

   public function displayInfo() {
      echo "Employee Name: $this->name \n";
      echo "Position: $this->position";
   }
}

// Create object of the class Employee and pass arguments to its constructor.
$emp = new Employee("John Doe", "Software Developer");
$emp->displayInfo(); // Calling method.
?>

Output:

Employee Name: John Doe 
Position: Software Developer

Modern Constructor Features in PHP (PHP 8+)


Modern PHP versions have introduced advanced features that make constructors more expressive, readable, and flexible.
These include:

  • Named Arguments
  • Union Types / Mixed Types
  • Default Values and Variadic Parameters

Let’s go through each one with suitable syntax and examples.

1. Named Arguments

PHP 8.0 introduced named arguments, which allow you to pass arguments to a constructor (or any function) by explicitly specifying the parameter name. This improves code readability, makes argument order irrelevant, and reduces errors.

Syntax

$object = new ClassName(paramName1: value1, paramName2: value2);

Example:

<?php
class Person {
   public string $name;
   public int $age;

   public function __construct(string $name, int $age) {
      $this->name = $name;
      $this->age = $age;
   }
   public function showDetails() {
       echo "Name: {$this->name}, Age: {$this->age}";
   }
}

// Passing argument to constructor using named arguments (order doesn’t matter).
$person = new Person(age: 30, name: "Alice");
$person->showDetails();
?>

Output:

Name: Alice, Age: 30

In this example, we have passed arguments to constructor’s parameters using their names rather than order. This feature is especially useful when constructors have many parameters or optional ones. It makes the code self-documenting and easy to maintain.

2. Default Values to Parameters

PHP allows you to assign default values for the optional parameters of the constructor. PHP 7.0+ introduced this feature. The general syntax is as:

public function __construct($param1 = "default") { ... }

Example:

<?php
class Product {
   public $name;
   public $price;
   public $category;
 
// Parameterized constructor with a default value.
   public function __construct($name, $price, $category = "General") {
      $this->name = $name;
      $this->price = $price;
      $this->category = $category;
   }

   public function displayInfo() {
      echo "Product name: " . $this->name . "\n";
      echo "Price: " . $this->price . "\n";
      echo "Product category: " . $this->category;
   }
}
// Create an object of class with passing arguments.
$laptop = new Product("Gaming Laptop", 1200);
$laptop->displayInfo();
?>

Output:

Product name: Gaming Laptop
Price: 1200
Product category: General

3. Variadic Parameters

A constructor can accept variadic arguments (…$args), which allow it to receive a variable number of arguments. This makes it possible to pass multiple values without defining each parameter explicitly. The general syntax is as:

public function __construct($param1 = "default", ...$args) { ... }

Example:

<?php
class Student {
   public $name;
   public $subjects;

// Constructor with variadic parameter.
   public function __construct($name, ...$subjects) {
      $this->name = $name;
      $this->subjects = $subjects;
   }
   public function displayInfo() {
      echo "Student Name: " . $this->name . "\n";
      echo "Enrolled Subjects: " . implode(", ", $this->subjects) ."\n";
   }
}

// Creating objects with a variable number of arguments.
$student1 = new Student("Alice", "Math", "Science");
$student2 = new Student("Bob", "History", "English", "Geography");

$student1->displayInfo();
$student2->displayInfo();
?>

Output:

Student Name: Alice
Enrolled Subjects: Math, Science
Student Name: Bob
Enrolled Subjects: History, English, Geography

In this example, we have defined a constructor with a regular parameter and a variadic parameter. In the constructor definition, $name is a regular parameter, and …$subjects is a variadic parameter that allows multiple arguments to be passed as an array.

You can pass any number of arguments during the object creation. The implode() function joins array elements into a comma-separated string for display.

4. Union Types / Mixed Types

Union types introduced in PHP 8.0 allow a constructor parameter to accept multiple possible types. This means a variable can hold more than one specified type. For example, int|string means the parameter can accept either an integer or a string. The general syntax is as:

public function __construct(int|string $param) {
   // Initialization code
}

In the above syntax, the constructor parameter $param can be either an integer or a string type.

Example:

<?php
class User {
   public $id;
   public $name;

// Constructor with union type parameters.
  public function __construct(int|string $id, string $name) {
     $this->id = $id;
     $this->name = $name;
  }
  public function displayInfo() {
     echo "User ID: " . $this->id . "\n";
     echo "User Name: " . $this->name . "\n";
  }
}

// Creating objects with different types for the parameter $id.
$user1 = new User(101, "Alice"); // int ID
$user2 = new User("U2025", "Bob"); // string ID

$user1->displayInfo();
$user2->displayInfo();
?>

Output:

User ID: 101
User Name: Alice
User ID: U2025
User Name: Bob

In this example, the constructor defines $id as int|string, meaning it can accept either an integer or a string. $user1 passes an integer (101), and $user2 passes a string (“U2025”). Both are valid — PHP doesn’t throw a type error.

Note (for advanced usage):

You can also combine more types:

public function __construct(int|float|string|null $value) { ... }

Or use the mixed type if you want to allow any data type:

public function __construct(mixed $data) { ... }

Conclusion

A constructor in PHP is a special method that gets invoked automatically when you create an object of a class. It plays a crucial role in initializing the object’s properties and setting up the object in a valid state.

You can define a constructor using the __construct() magic method. Although constructors are not mandatory in PHP classes, they are very useful for ensuring that an object is properly initialized at the time of creation.

Without a constructor, you would need to manually set each property after creating the object, which can make your code more complex and error-prone.

We hope this guide has helped you understand constructors in PHP, including their syntax, characteristics, types, and examples, so you can use them in your own projects.