Countable usage example of PHP standard library (SPL)

coldplay.xixi
Release: 2023-04-09 08:10:01
forward
2320 people have browsed it

Countable usage example of PHP standard library (SPL)

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

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

Interface summary

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

When If a class implements the Countable interface and implements the count method in the interface, you can directly use the value returned by the count method in count(Object).

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 obviously not the result we want. Next, implement the Countable interface and 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

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

Related learning recommendations: PHP programming from entry to proficiency

The above is the detailed content of Countable usage example of PHP standard library (SPL). 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!