PHP Reference ยท Standard PHP Library and Classes
The Countable interface
Reference for the PHP Countable interface: make count() work on your own objects, the single count() method, return rules and common mistakes.
Countable is a one-method interface. When a class implements it, the built-in count() function (and its alias sizeof()) calls the object's count() method and returns the result. Without the interface, count($object) throws a TypeError.
Use it for collection-like classes (a cart, a result set, a typed list) so callers can ask for the size the same way they do for an array.
class Cart implements Countable { public function count(): int { return 3; } } echo count(new Cart()); // 3
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
interface Countable { public function count(): int; }
| Name | Description |
|---|---|
Countable::count() |
Takes no parameters. Returns the number of elements as an int. |
Return value: an integer. count($object) returns exactly what your method returns.
Errors / Exceptions: count() throws TypeError for an argument that is neither an array nor a Countable.
Usage notes
- Declare the return type
: int. The interface requires it, so an implementation without a compatible return type is a fatal error. - Only
count()uses it.Countabledoes not make an object iterable or array-like. Combine it withIteratorAggregateorArrayAccessif you want those as well. COUNT_RECURSIVEonly descends into arrays. ACountableobject inside an array counts as one element, not as its owncount(); the second example prints 2 and then 5 (two elements plus the three nested values).- The result is not cached.
count()runs your method every call, so make it cheap (return a stored counter orcount($this->items)). empty($object)ignores it. An object is always non-empty forempty(). Testcount($obj) === 0yourself.- Built-in classes such as
ArrayObject,SplStack,SplObjectStorageandSplFixedArrayalready implementCountable. - Since PHP 8.0
count()on a non-countable value throws instead of warning.