CKTIS / PHP
Countable
Supply count(): int so the global count function can ask an object for its size.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
class Basket implements CountableSupply count(): int so the global count function can ask an object for its size. The implementation defines what is counted, which may differ from the number of public properties. Implementing Countable alone does not make the object Traversable.
class Basket implements Countable { public function __construct(private array $items){} public function count(): int{return array_sum($this->items);} }
$b=new Basket(["pears"=>2,"figs"=>3]); echo json_encode([count($b),is_countable($b),is_iterable($b)]);
[5,true,false]
Examples
<?php
class Basket implements Countable { public function __construct(private array $items){} public function count(): int{return array_sum($this->items);} }
$b=new Basket(["pears"=>2,"figs"=>3]); echo json_encode([count($b),is_countable($b),is_iterable($b)]);
Result
[5,true,false]