Constructors
The __construct method runs automatically when an object is created.
Syntax
public function __construct($value) {
$this->value = $value;
}A constructor is a special method named __construct() that runs the moment an object is created. It is the perfect place to set up the object's initial properties.
PHP 8 supports constructor property promotion, which declares and assigns properties directly in the constructor signature.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Inject a database connection into a Repository class via the constructor so the object is ready to use immediately.
- Use constructor promotion to declare and initialise all Product properties in a single concise signature.
- Validate that an email address is well-formed inside the constructor before the User object is created.
More examples
Basic constructor
__construct runs automatically when new User() is called, setting up the object's initial state.
<?php
class User {
public string $name;
public string $email;
public function __construct(string $name, string $email) {
$this->name = $name;
$this->email = $email;
}
}
$user = new User('Alice', '[email protected]');
echo $user->email;Constructor promotion (PHP 8)
Constructor promotion declares, assigns, and optionally marks properties in one place, eliminating boilerplate.
<?php
class Product {
public function __construct(
public readonly string $name,
public readonly float $price,
public int $stock = 0
) {}
}
$p = new Product('Widget', 9.99, 50);
echo "{$p->name}: {$p->price} ({$p->stock} in stock)";Validation inside the constructor
Throwing in the constructor prevents invalid objects from ever being created, enforcing invariants at construction time.
<?php
class Email {
public readonly string $address;
public function __construct(string $address) {
if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException("Invalid email: $address");
}
$this->address = $address;
}
}
try {
$e = new Email('not-an-email');
} catch (InvalidArgumentException $ex) {
echo $ex->getMessage();
}
Discussion