您现在的位置是:首页 > 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)
相关文章
随机图文
-
php技术提升心得与方法
现在的PHP市场虽然充斥了大量的的PHP开发人员,但这些人当中真正能称得上高手的却寥寥无几。很多公司虽然招聘了一些PHP开发人员,但是由于技术水平不高,导致公司的项目一直堆积。这不仅另公司无奈也让已经入职的PHP开发人员着急,他们也想要在PHP领域更近一步,但却苦于找不到提高自己的方法,下面我们的鸥仔收集了一些PHP大神的一些工作方式、习惯,让大家看看PHP大神们是如何工作,也希望这些方法能帮助到那些想要在PHP领域更近一步的人。 -
开怀一笑,让你开心的幽默故事三则
1.信不信由你 现在让骗子闹的人们对任何事情都不敢轻信,真是多次被忽悠,遇事要三思。如果拿着一瓶矿泉水告诉你,这是某某大师施过法术的,可以益寿延年,你肯定不信,如果说这瓶水经过高科技纳米技术处理,又由美国科学院认证,你八成就信了。 你爱人买了件连衣裙,大家都说她穿上真好看,她不一定信,如果有一个说她穿上不好看,她肯定信了。 明星访谈,说他们夫妻如何相亲相爱,你大概不太相信,如果有人说他们俩闹 -
PHP8.2新特性 弃用动态属性,更加严谨
PHP8.2新特性弃用动态属性,更加严谨,动态属性的创建已被弃用,以帮助避免错误和拼写错误,除非该类通过使用#[\AllowDynamicProperties]属性来选择。stdClass允许 -
PHP8.1新特性枚举 枚举的简单用法
PHP8.1新特性枚举枚举的简单用法1.枚举类型的定义 enumStatus:int { caseDraft=1; casePublished=2; case