Skip to content

Chapter 18 of 38

Constructors and Destructors

Initialize dependencies and understand promotion, lifecycle hooks, and cleanup limits.

36 minutes 10 quick checksBy Subha Prasad
Lesson 18 of 38Course navigation

Lesson content

Read, practise, then check your understanding

__construct establishes invariants and PHP 8 promotion can declare properties from parameters. Throwing prevents invalid construction.

Practical example

<?php
final class UserService {
  public function __construct(private readonly PDO $database, private readonly LoggerInterface $logger) {}
}

__destruct timing/order can be unreliable, especially during shutdown. Do not depend on it for commits, critical flushes, or locks; use explicit cleanup and finally. Avoid heavy I/O or publishing $this during construction.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes __construct?
Which PHP term matches this description: The magic method called during object construction.
Which statement best describes property promotion?
Which PHP term matches this description: Constructor parameter syntax that also declares and initializes a property.
Which statement best describes __destruct?
Which PHP term matches this description: A nondeterministically timed cleanup hook near object or request teardown.
Which statement best describes dependency injection?
Which PHP term matches this description: Supplying collaborators from outside during construction.
Which statement best describes invariant?
Which PHP term matches this description: A condition every successfully constructed object must preserve.

0 of 10 checks passed

Your progress is saved on this device.