PHP Countable 接口和 Iterator 接口

教程 shanhuhai 5574℃ 3评论

经常使用接口(Interface)的好处是,别人只要看你的接口就知道你的类实现了哪些功能提供了哪些方法。PHP 提供了一些内置的接口,用来解决一些典型的问题

今天介绍两个接口,CountableIterator

Countable (计数器接口)

Countable 接口很简单,如果你的类需要一个统计对象内部某些元素个数的方法你可以实现 Countable 接口

<?php
/**
 * Author: shanhuhai
 * Date: 2017/9/16 23:07
 * Mail: 441358019@qq.com
 */

class User implements Countable {

    private $container = [];

    public function insert($name){
        array_push($this->container, $name);
    }

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

}

$user = new User();
$user->insert("Shanhuhai");
$user->insert("Wudy");
echo $user->count().PHP_EOL;

Iterator (迭代器接口)

如果你想让你的对象能够使用 foreach 将其中的某些数据循环出来,你可以将类实现 Iterator接口。

下面的例子展现了当你的类继承 Iterator 接口后内部方法执行的细节,很神奇是不是,好像你的对象变成了一个数组一样,能够被循环打印出来。

<?php
/**
 * Author: shanhuhai
 * Date: 2017/9/16 23:07
 * Mail: 441358019@qq.com
 */

class User implements Iterator {
    private $position = 0;
    private $container = array(
        "Shanhuhai",
        "Rudy",
        "Nash",
    );

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

    public function rewind() {
        var_dump(__METHOD__);
        $this->position = 0;
    }

    public function current() {
        var_dump(__METHOD__);
        return $this->container[$this->position];
    }

    public function key() {
        var_dump(__METHOD__);
        return $this->position;
    }

    public function next() {
        var_dump(__METHOD__);
        ++$this->position;
    }

    public function valid() {
        var_dump(__METHOD__);
        return isset($this->container[$this->position]);
    }
}

$it = new User;

foreach($it as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}


转载请注明:大后端 » PHP Countable 接口和 Iterator 接口

付费咨询
喜欢 (4)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(3)个小伙伴在吐槽
  1. 这例子中,即使不继承coutable也能使用对象count方法呀
    ccjian372019-07-01 00:11 回复
  2. countable 这个例子下的 echo $user->count() 应该改为 count($user) 或 sizeof($user) 。 因为这个例子好像和 Countable 接口没多大关系,即使不 implements Countable, $user->count() 肯定也能计算出 container 数组的元素个数
    cxl2017-10-08 11:02 回复
    • 多谢提醒,已修改!
      shanhuhai2017-10-15 13:35 回复