您现在的位置是:首页 > PHP框架交流PHP框架交流

php把对象count 统计 实现Countable计算数量 php进阶

上善若水2022-01-02 16:04:55【PHP框架交流】 1481人已围观

简介php把对象count 统计 count计算数量,我们知道一般count作用于数量,用于计算数组里面的元素数量, class A implements \Countable { /**

php把对象count 统计 count计算数量,我们知道一般count作用于数量,用于计算数组里面的元素数量,

class A implements \Countable
{
    /**
     * @var array $data
     */
    public $data = [];

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

$a = new  A();
$array = ['ak' => 'a'];
print_r(count($array));

如图就可以轻松实现对一个对象调用count() 函数了.打印结果为

/**
 * Counts all elements in an array, or something in an object.
 * <p>For objects, if you have SPL installed, you can hook into count() by implementing interface {@see Countable}.
 * The interface has exactly one method, {@see Countable::count()}, which returns the return value for the count() function.
 * Please see the {@see Array} section of the manual for a detailed explanation of how arrays are implemented and used in PHP.</p>
 * @link https://php.net/manual/en/function.count.php
 * @param array|Countable $value The array or the object.
 * @param int $mode [optional] If the optional mode parameter is set to
 * COUNT_RECURSIVE (or 1), count
 * will recursively count the array. This is particularly useful for
 * counting all the elements of a multidimensional array. count does not detect infinite recursion.
 * @return int the number of elements in var, which is
 * typically an array, since anything else will have one
 * element.
 * <p>
 * If var is not an array or an object with
 * implemented Countable interface,
 * 1 will be returned.
 * There is one exception, if var is null,
 * 0 will be returned.
 * </p>
 * <p>
 * Caution: count may return 0 for a variable that isn't set,
 * but it may also return 0 for a variable that has been initialized with an
 * empty array. Use isset to test if a variable is set.
 * </p>
 */
#[Pure]
function count(Countable|array $value, int $mode = COUNT_NORMAL): int {}

源码内部就是Countable|array就可以调用这个方法.

很赞哦! (2)

相关文章

随机图文

文章评论

站点信息

  • 建站时间:2019-10-24
  • 网站程序:Thinkphp6 Layui
  • 文章统计247篇文章
  • 标签管理标签云
  • 统计数据cnzz统计
  • 微信公众号:扫描二维码,关注我们