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

PHP SPL standard library Countable

Guanhui
Release: 2023-04-08 22:46:02
forward
2422 people have browsed it

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
}
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template