Interface constants in PHP - Time & Space Complexity
Let's see how using constants inside interfaces affects the time it takes for a program to run.
We want to know how the program's work changes when it uses these constants.
Analyze the time complexity of the following code snippet.
interface Status {
const ACTIVE = 1;
const INACTIVE = 0;
}
function checkStatus(int $status): string {
return $status === Status::ACTIVE ? 'Active' : 'Inactive';
}
$result = checkStatus(Status::ACTIVE);
This code defines constants inside an interface and uses them in a function to check a status value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing interface constants and a simple comparison.
- How many times: The function runs once here, so one comparison and one constant access.
Since the code only does a single check using constants, the work stays the same no matter how many constants exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 comparison, 1 constant access |
| 100 | 1 comparison, 1 constant access |
| 1000 | 1 comparison, 1 constant access |
Pattern observation: The number of operations does not grow with input size; it stays constant.
Time Complexity: O(1)
This means the time to run this code stays the same no matter how many constants or inputs there are.
[X] Wrong: "Accessing interface constants takes longer as more constants are added."
[OK] Correct: Constants are fixed values stored in a way that accessing them is always quick and does not depend on how many constants exist.
Understanding that constants in interfaces are accessed quickly helps you explain how your code handles fixed values efficiently, a useful skill in many programming tasks.
"What if the function checked multiple constants in a loop? How would the time complexity change?"