Properties and visibility in PHP - Time & Space Complexity
Let's see how accessing and modifying properties with different visibility affects the time it takes for a PHP program to run.
We want to know how the number of operations changes when we work with properties marked public, protected, or private.
Analyze the time complexity of the following code snippet.
class Example {
private int $count = 0;
public function increment(): void {
$this->count++;
}
public function getCount(): int {
return $this->count;
}
}
$example = new Example();
for ($i = 0; $i < 1000; $i++) {
$example->increment();
}
echo $example->getCount();
This code defines a class with a private property and methods to change and read it. Then it increments the property 1000 times and prints the result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
increment()method which increases the private property. - How many times: The loop runs 1000 times, so the increment happens 1000 times.
Each time we increase the input size (number of increments), the number of operations grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: If you double the number of increments, the work doubles too. It grows in a straight line.
Time Complexity: O(n)
This means the time to run grows directly with how many times you increment the property.
[X] Wrong: "Accessing private properties is slower and adds extra hidden loops, so it changes the time complexity."
[OK] Correct: Accessing private properties is a simple operation done in constant time. It does not add loops or repeated work, so it does not affect how the total time grows with input size.
Understanding how property visibility affects performance helps you write clear and efficient code. It shows you know how PHP handles data inside objects, which is a useful skill in many coding tasks.
"What if we changed the private property to public and accessed it directly inside the loop? How would the time complexity change?"