文字

The Countable interface

(PHP 5 >= 5.1.0)

简介

类实现 Countable 可被用于 count() 函数.

接口摘要

Countable {
abstract public int count ( void )
}

Table of Contents

  • Countable::count — 统计一个对象的元素个数

用户评论:

[#1] Anonymous [2011-01-17 06:10:43]

Note that arrays don't implement countable. Therefore you can't force a countable parameter for a function if you want it also to work with native arrays.

[#2] isaac dot z dot foster dot nada at spamporfav dot gmail dot com [2010-06-08 01:18:36]

I just want to point out that your class has to actually implement the Countable interface, not just define a count method, to be able to use count($object) and get the expected results. I.e. the first example below won't work as expected, the second will. (The normal arrow function accessor ($object->count()) will work fine, but that's not the kewl part :) )

<?php
//Example One, BAD :(

class CountMe
{

    protected 
$_myCount 3;

    public function 
count()
    {
        return 
$this->_myCount;
    }

}

$countable = new CountMe();
echo 
count($countable); //result is "1", not as expected

//Example Two, GOOD :)

class CountMe implements Countable
{

    protected 
$_myCount 3;

    public function 
count()
    {
        return 
$this->_myCount;
    }

}

$countable = new CountMe();
echo 
count($countable); //result is "3" as expected
?>

上一篇: 下一篇: