SPL 的 Countable 接口允许实现了接口的类的对象作为 count() 函数的参数,以此来达到语义上的“计数”能力。
没啥好说的…直接上代码吧…很简单…主要就是要实现 Countable 接口的 public function count() 方法。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 
 | <?php
 class SystemError implements Countable
 {
 /**
 * 错误列表
 * @var array
 */
 protected static $error = [];
 
 /**
 * @var static
 */
 protected static $instance;
 
 /**
 * 实现 Countable 的 count 方法
 * @return int
 */
 public function count()
 {
 return count(self::$error);
 }
 
 /**
 * 添加一个错误
 * @param $error
 */
 public function addError($error)
 {
 static::$error[] = $error;
 return $this;
 }
 
 /**
 * 单例模式
 * @return SystemError
 */
 public static function instance()
 {
 return static::$instance ?: static::$instance = new static;
 }
 
 protected function __construct()
 {
 
 }
 
 protected function __clone()
 {
 return self::instance();
 }
 }
 
 | 
实现了 Countable 接口之后,可以使用 count() 函数
或者 $obj->count() 来获取 public function count() 中的返回值
 
