您现在的位置是:首页 > PHP框架交流PHP框架交流
php把对象count 统计 实现Countable计算数量 php进阶
上善若水2022-01-02 16:04:55【PHP框架交流】
2067人已围观
简介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)
相关文章
随机图文
php把对象foreach 循环 Iterator遍历对象 php进阶
php高级技术把一个对象foreach循环遍历,很多框架中都实现了Iterator 然后就可以foreach去遍历这个对象,下面简单尝试编写一个简单的demo去循环遍历对象. class A implSpringBoot 使用Test调试项目 idea快速创建Junit test测试类
我们在SpringBoot项目中经常会频繁使用到项目调试整个项目启动起来调试十分繁琐,用idea可以快捷帮助我们创建测试类快速进行测试.首先,我们在需要测试的方法或者类文件上右键,选择goto->Tphp技术提升心得与方法
现在的PHP市场虽然充斥了大量的的PHP开发人员,但这些人当中真正能称得上高手的却寥寥无几。很多公司虽然招聘了一些PHP开发人员,但是由于技术水平不高,导致公司的项目一直堆积。这不仅另公司无奈也让已经入职的PHP开发人员着急,他们也想要在PHP领域更近一步,但却苦于找不到提高自己的方法,下面我们的鸥仔收集了一些PHP大神的一些工作方式、习惯,让大家看看PHP大神们是如何工作,也希望这些方法能帮助到那些想要在PHP领域更近一步的人。精品笑话十则,总有一则逗乐您
1、一漂亮女同事,她老公给她送午饭,没说话,放下就走了。 新来的男同事问:刚才那是谁啊? 她回答:送外卖的。 新来又问:怎么沒给钱? 她说:不用给,晚上陪他睡觉就好了。 男同事沉默了。第二天,给她带了四菜一汤的午饭。 整个办公室轰然大笑…… 2、下午肚子饿,看见同事桌上有瓶酸奶,想都没想就喝了。 一会儿,同事来了大叫道:“我的洗面奶怎么不见了!108块啊!” 哥没说话,只是默默的