您现在的位置是:首页 > PHP框架交流PHP框架交流
php把对象count 统计 实现Countable计算数量 php进阶
上善若水2022-01-02 16:04:55【PHP框架交流】 1923人已围观
简介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)
相关文章
随机图文
-
ThinkPHP6上传图片七牛云
ThinkPHP6如何上传图片七牛云,如何上传文件到七牛云对象储存cos,总所周知图片是特别消耗网站带宽的,个人网站将图片上传至七牛云才能显著提升网站的响应速度,手把手交大家如何上配置ThinkPHP -
docker拉取镜像 missing signature key
Trying to pull repository docker.io/library/nginx … missing signature key 查看当前docker版本都显示1.13的版本,那还真 -
2022年面试前基本准备1
面试题准备1.Mysql中MyISAM和InnoDB的区别有哪些?区别: InnoDB支持事务,MyISAM不支持事务。这是MySQL将默认存储引擎从MyISAM变成Inno -
冠状病毒科普 什么是冠状病毒
冠状病毒在分类层级上是科,冠状病毒科拉丁文名Coronaviridae, 简称CoV,因为外形呈球状,具有花瓣状的刺突,因此根据其形状,国际病毒命名委员会在1975年正式命名为“冠状病毒科”。目前已知