0
0
PHPprogramming~5 mins

Constructor method in PHP - Time & Space Complexity

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

We want to understand how the time it takes to run a constructor method changes as the input grows.

Specifically, does creating an object take more time if we give it more data?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Person {
    public string $name;
    public int $age;

    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$person = new Person("Alice", 30);
    

This code creates a Person object and sets its name and age when it is made.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Assigning values to object properties.
  • How many times: Exactly twice here, once for each property.
How Execution Grows With Input

As the number of properties to set grows, the time to run the constructor grows in a straight line.

Input Size (number of properties)Approx. Operations
22 assignments
1010 assignments
100100 assignments

Pattern observation: The time grows directly with the number of properties set.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the object grows in a straight line with the number of properties we assign.

Common Mistake

[X] Wrong: "Constructors always run in constant time no matter what."

[OK] Correct: If the constructor sets many properties or processes large input, it takes longer. The time depends on what the constructor does.

Interview Connect

Understanding how constructors scale helps you explain object creation costs clearly and shows you think about code efficiency in real projects.

Self-Check

"What if the constructor loops over an array of items to set properties? How would the time complexity change?"