Home >Backend Development >PHP Tutorial >PHP SPL standard library Countable

PHP SPL standard library Countable

Guanhui
Guanhuiforward
2020-06-20 17:50:552436browse

PHP SPL standard library Countable

The example in this article describes the usage of PHP Standard Library (SPL)-Countable. Share it with everyone for your reference, the details are as follows:

The class implements Countable and can be used in the count() function.

Interface Summary


Countable {
/* 方法 */
abstract public count ( void ) : int
}

When a class implements the Countable interface and implements the count method in the interface, it can directly use count(Object) to return the count method value.

Example:


class MyCount 
{
 private $num;

 public function __construct($num) 
 {
 $this->num = $num;
 }

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

$obj = new MyCount(10);

echo count($obj);//返回1

The above result is expected, but it is obviously not the result we want. Let’s implement it next Countable interface try again:


class MyCount implements \Countable
{
 private $num;

 public function __construct($num) 
 {
 $this->num = $num;
 }

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

$obj = new MyCount(10);

echo count($obj);//返回10

After implementing the Countable interface, use count() to trigger the count method in the class, thus getting the returned 10.

Recommended tutorial: "PHP"


The above is the detailed content of PHP SPL standard library Countable. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete