The __construct Method

The __construct method is a special class method that is automatically called when creating a new object. It is used to initialize object properties or perform other initial settings. Unlike regular methods, the constructor does not need to be called explicitly.

Syntax

phpclass ClassName {
  public function __construct([parameters]) {
    // initialization code
  }
}

Example

Let's create a simple class with a constructor that sets the $name property:

php<?php
class User {
  public $name;
  
  public function __construct($name) {
    $this->name = $name;
  }
}

$user = new User('John');
echo $user->name;
?>

Code execution result:

php'John'

Example

The constructor can accept multiple parameters and perform complex initialization:

php<?php
class Product {
  public $id;
  public $price;
  
  public function __construct($id, $price) {
    $this->id = $id;
    $this->price = $price * 1.2; // Adding 20% VAT
  }
}

$product = new Product(101, 100);
echo $product->price;
?>

Code execution result:

php120

See Also

  • the __destruct method,
    which is called when an object is destroyed
  • the __clone method,
    which is called when cloning an object