I'll also share some thoughts on this question.
First, the example on php.net is incorrect from an OOP perspective because it violates a couple of principles at once. Yes, it demonstrates the concept of Countable, but in a misleading way.
A more proper approach should look like this:
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";
}
This is a proper OOP approach, where count() simply returns the number of elements, and increment() is used to change the state of the object.
The second point to consider is how you organize your code. If you're strictly using type hints and working with an object that implements Countable, the correct way to interact with it is via $object->count(). If you're unsure whether the object is Countable or just an array, then count($object) is acceptable, but ideally, you should handle this with proper type checking.
count()function returns the amount of times. So not really.count" - do you mean the function contained withinmyCounter, or do you mean the PHP function,count? One has access to$count, the other doesn't...count()function on an object implementing Countable.$counter->count(), right?$counter->count().