First, the commonly referenced example of Countable is somewhat misleading from an OOP perspective, as it unintentionally violates some key principles. While it demonstrates the concept of Countable, it does so in a way that could cause confusion.
According to the Countable interface:
<?php
#[TentativeType]
public function count(): int;
?>
This means that the `count()` method should not modify the state of an object—it should simply return an integer value, aligning with SOLID principles.
A proper OOP approach would be:
<?php
class Counter implements Countable
{
private $count = 0;
public function count(): int
{
return $this->count;
}
public function increment(): void
{
$this->count++;
}
}
$counter = new Counter;
for ($i = 0; $i < 10; ++$i) {
$counter->increment();
echo "I have been incremented " . count($counter) . " times\n";
}
?>
Here, count() correctly returns the number of elements, while increment() is responsible for modifying the state of the object.
A separate discussion can be had about whether to use count($object) or $object->count(), but that’s a different topic.