Home > Article > Backend Development > 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.
Countable { /* 方法 */ abstract public count ( void ) : int }
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)
.
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 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
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!