PHP IteratorAggregate,Countable接口

namespace Symfony\Component\HttpFoundation;

/**
 * ParameterBag is a container for key/value pairs.
 * ParameterBag 继承实现这两个接口
 * @author Fabien Potencier <fabien@symfony.com> 
 */
class ParameterBag implements \IteratorAggregate, \Countable
{
/**
 * Interface to create an external Iterator.
 * IteratorAggregate  需要实现 getIterator 方法,通常返回迭代器 ArrayIterator 类实例
 * @link https://php.net/manual/en/class.iteratoraggregate.php
 */
interface IteratorAggregate extends Traversable {

    /**
     * Retrieve an external iterator
     * @link https://php.net/manual/en/iteratoraggregate.getiterator.php
     * @return Traversable An instance of an object implementing <b>Iterator</b> or
     * <b>Traversable</b>
     * @since 5.0.0
     */
    public function getIterator();
}

/**
 * Classes implementing <b>Countable</b> can be used with the
 * <b>count</b> function.
 * 需实现count 方法
 * @link https://php.net/manual/en/class.countable.php
 */
interface Countable {

    /**
     * Count elements of an object
     * @link https://php.net/manual/en/countable.count.php
     * @return int The custom count as an integer.
     * </p>
     * <p>
     * The return value is cast to an integer.
     * @since 5.1.0
     */
    public function count();
}
class Test implements IteratorAggregate,Countable {

    protected $data = [
        'name'=>'学无止境',
        'age'=>26
    ];

    public function getIterator(){
        return new ArrayIterator($this->data);
    }

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

$test = new Test();

//遍历触发getIterator返回迭代器
foreach ($test as $key=>$value){
    echo $key.':'.$value.'<br/>';
}

//输出  name:学无止境
//      age:26

//触发 $test->count() 方法 输出 2
echo count($test);
class Test implements IteratorAggregate{
     public $name = '学无止境';
     protected $age = 26;
     public function getIterator(){
         return new ArrayIterator($this);
     }
}

//也可以遍历自身public属性
foreach ((new Test()) as $key=>$value){
    echo 'key:'.$key.':'.$value.'<br/>';
}
//只输出 name:学无止境
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值