PHP Conference Japan 2024

Countable::count

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Countable::count計算物件的元素數量

說明

public Countable::count(): int

當在實作 Countable 介面的物件上使用 count() 函式時,會執行此方法。

參數

此函式沒有參數。

回傳值

自訂的計數,以 int 型別回傳。

注意事項:

回傳值會被轉換為 int 型別。

範例

範例 #1 Countable::count() 範例

<?php
class myCounter implements Countable {
private
$count = 0;
public function
count() {
return ++
$this->count;
}
}

$counter = new myCounter;

for(
$i=0; $i<10; ++$i) {
echo
"我已被 count() 計算了 " . count($counter) . " 次\n";
}
?>

上述範例將輸出類似以下的內容:

I have been count()ed 1 times
I have been count()ed 2 times
I have been count()ed 3 times
I have been count()ed 4 times
I have been count()ed 5 times
I have been count()ed 6 times
I have been count()ed 7 times
I have been count()ed 8 times
I have been count()ed 9 times
I have been count()ed 10 times

新增註釋

使用者貢獻的註釋 1 則註釋

SenseException
10 年前
即使在實作 Countable 介面的物件於 count() 函式中使用時會呼叫 Countable::count 方法,count 的第二個參數 $mode 對您的類別方法沒有影響。

$mode 不會傳遞給 Countable::count

<?php

class Foo implements Countable
{
public function
count()
{
var_dump(func_get_args());
return
1;
}
}

count(new Foo(), COUNT_RECURSIVE);

?>

var_dump 輸出

array(0) {
}
To Top