0
0
PHPprogramming~5 mins

Constructor promotion in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constructor promotion
O(n)
Understanding Time Complexity

Let's see how the time it takes to run a constructor with promoted properties changes as we create more objects.

We want to know how the work grows when we make many instances using constructor promotion.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class User {
    public function __construct(
        public string $name,
        public int $age
    ) {}
}

$users = [];
for ($i = 0; $i < $n; $i++) {
    $users[] = new User("Name$i", $i);
}
    

This code creates $n User objects using constructor promotion to set properties quickly.

Identify Repeating Operations
  • Primary operation: Creating a new User object with promoted properties inside the loop.
  • How many times: The loop runs exactly $n times, creating $n objects.
How Execution Grows With Input

Each new object takes a small fixed time to create. As we increase $n, the total time grows proportionally.

Input Size (n)Approx. Operations
1010 object creations
100100 object creations
10001000 object creations

Pattern observation: Doubling the number of objects doubles the work done.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all objects grows directly with the number of objects we make.

Common Mistake

[X] Wrong: "Using constructor promotion makes object creation take constant time no matter how many objects."

[OK] Correct: Each object still needs to be created one by one, so total time grows with the number of objects.

Interview Connect

Understanding how object creation scales helps you explain performance in real projects and shows you know how code behaves as it grows.

Self-Check

"What if we added a loop inside the constructor that runs $m times? How would the time complexity change?"