您现在的位置是:首页 > PHP框架交流PHP框架交流
php把对象count 统计 实现Countable计算数量 php进阶
上善若水2022-01-02 16:04:55【PHP框架交流】 1502人已围观
简介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领域更近一步的人。 -
PHP8.0新特性(3) 构造器属性提升 简单写法
PHP8.0新特性(3) 构造器属性提升 简单写法,写法更加简洁,直接定义到构造器传参的参数上了。新版写法 class Point { public function __construct( -
ThinkPHP6.0 搜索器
搜索器的作用是用于封装字段(或者搜索标识)的查询条件表达式,一个搜索器对应一个特殊的方法(该方法必须是public类型),方法命名规范为:searchFieldNameAttrFieldName为数据 -
php技术提升心得与方法
现在的PHP市场虽然充斥了大量的的PHP开发人员,但这些人当中真正能称得上高手的却寥寥无几。很多公司虽然招聘了一些PHP开发人员,但是由于技术水平不高,导致公司的项目一直堆积。这不仅另公司无奈也让已经入职的PHP开发人员着急,他们也想要在PHP领域更近一步,但却苦于找不到提高自己的方法,下面我们的鸥仔收集了一些PHP大神的一些工作方式、习惯,让大家看看PHP大神们是如何工作,也希望这些方法能帮助到那些想要在PHP领域更近一步的人。