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:学无止境