0
0
PHPprogramming~5 mins

Access modifiers (public, private, protected) in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Access modifiers (public, private, protected)
O(1)
Understanding Time Complexity

When using access modifiers in PHP, it's helpful to understand how they affect the way code runs.

We want to see how the choice of public, private, or protected changes the number of steps the program takes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Example {
    private array $data;

    public function __construct(array $items) {
        $this->data = $items;
    }

    public function getItem(int $index) {
        return $this->data[$index];
    }
}

$example = new Example(range(1, 1000));
echo $example->getItem(500);
    

This code stores a list of items privately and allows public access to get one item by index.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing an array element by index.
  • How many times: Each call to getItem accesses one element directly, no loops involved.
How Execution Grows With Input

Accessing an item by index takes the same steps no matter how big the array is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The number of steps stays the same even if the list grows larger.

Final Time Complexity

Time Complexity: O(1)

This means accessing data with these modifiers takes a constant amount of time regardless of the data size.

Common Mistake

[X] Wrong: "Using private or protected makes data access slower because it restricts visibility."

[OK] Correct: Access modifiers control who can see or change data, but they do not add extra steps when accessing data inside the class.

Interview Connect

Understanding how access modifiers affect code helps you write clear and efficient programs, a skill valued in many coding challenges and real projects.

Self-Check

"What if the getItem method used a loop to find the item instead of direct access? How would the time complexity change?"