Constructor promotion in PHP - Time & Space 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.
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.
- 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.
Each new object takes a small fixed time to create. As we increase $n, the total time grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: Doubling the number of objects doubles the work done.
Time Complexity: O(n)
This means the time to create all objects grows directly with the number of objects we make.
[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.
Understanding how object creation scales helps you explain performance in real projects and shows you know how code behaves as it grows.
"What if we added a loop inside the constructor that runs $m times? How would the time complexity change?"