note 130241 added to countable.count
| From: | moris@moris.org.ua | Date: | Wed, 09 Apr 2025 18:47:51 +0000 |
| Subject: | note 130241 added to countable.count | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-222079@lists.php.net to get a copy of this message | ||
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
/**
* Count elements of an object
* @link https://php.net/manual/en/countable.count.php
* @return int<0,max> The custom count as an integer.
* <p>
* The return value is cast to an integer.
* </p>
*/
#[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;
// Returns the item count of the object
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.
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 79.194.221.163)
----
Manual Page -- https://php.net/manual/en/countable.count.php
Edit -- https://main.php.net/note/edit/130241
Del: integrated -- https://main.php.net/note/delete/130241/integrated
Del: useless -- https://main.php.net/note/delete/130241/useless
Del: bad code -- https://main.php.net/note/delete/130241/bad+code
Del: spam -- https://main.php.net/note/delete/130241/spam
Del: non-english -- https://main.php.net/note/delete/130241/non-english
Del: in docs -- https://main.php.net/note/delete/130241/in+docs
Del: other reasons-- https://main.php.net/note/delete/130241
Reject -- https://main.php.net/note/reject/130241
Search -- https://main.php.net/manage/user-notes.php