Countable::count()

继承 Countable 接口的类中,用于返回对象中元素的数量

首字母:C

函数名称:Countable::count()

适用版本:PHP 5.3.0 及以上版本

用法:int Countable::count ( void )

说明:Countable::count() 函数用于继承 Countable 接口的类中,用于返回对象中元素的数量。

参数:无

返回值:返回对象中元素的数量,类型为整型。

示例:

class MyList implements Countable {
 private $items = array(); // 存储列表元素的数组
 // 添加元素到列表中
 public function add($item) {
 $this->items[] = $item;
 }
 // 实现 Countable 接口中的 count 方法
 public function count() {
 return count($this->items);
 }
}
$list = new MyList();
$list->add("Apple");
$list->add("Banana");
$list->add("Cherry");
echo $list->count(); // 输出:3

在上面的示例中,我们创建了一个自定义类 MyList,该类实现了 Countable 接口并实现了接口中的 count() 方法。该方法中使用 count() 函数来返回 $items 数组中元素的数量,从而实现了自定义对象的计数功能。最后,我们创建了一个 MyList 对象 $list 并使用 count() 方法输出了对象中元素的数量。

同首字母函数