🐘 PHP Intermediate

What is PHP's Countable interface?

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.