What is PHP's Countable interface?
Why Interviewers Ask This
This tests whether you can apply PHP knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
The Countable interface allows objects to be used with PHP's built-in count() function. Implement the single required method: public function count(): int — this returns the count when count($yourObject) is called. Example: a custom collection class that wraps an array and implements Countable so that count($collection) works naturally. Laravel's Collection class implements Countable along with Iterator and ArrayAccess, making it behave like a native PHP array in most contexts. Combined with the Stringable interface (implementing __toString(), formalized in PHP 8.0), these interfaces let custom objects blend seamlessly with built-in PHP functions and language constructs.
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex PHP answers easy to follow.
Previous
What is PHP's arrow function and how does it differ from a closure?
Next
What is PHP session security best practices?