Iterator
当我们在数据库中读取大量数据时,迭代器通常被用来方便数据管理。classBasketimplementsIterator{
private$fruits=array('apple','banna','pear','orange','watermelon');
private$position=0;
//返回当前元素
publicfunctioncurrent(){
return$this->fruits[$this->position];
}
//返回当前键
publicfunctionkey(){
return$this->position
}
//下移一个元素
publicfunctionnext(){
$this->position;
}
///移动到第一个元素
publicfunctionrewind(){
$this->position=0;
}
///判断后续是否有元素
publicfunctionvalid(){
returnisset($this->fruits[$this->position 1]);
}
}
ArrayAccess
使对象中的数据能够像数组一样访问classobjimplementsArrayAccess{
private$container=array();
publicfunction__construct(){
$this->container=array(
"one"=>1,
"two"=>2,
"three"=>3
);
}
//赋值
publicfunctionoffsetSet($offset,$value){
if(is_null($offset)){
$this->container[]=$value;
}else{
$this->container[$offset]=$value;
}
}
//某键是否存在
publicfunctionoffsetExists($offset){
returnisset($this->container[$offset]);
}
///删除键值
publicfunctionoffsetUnset($offset){
unset($this->container[$offset]);
}
//获取键对应的值
publicfunctionoffsetGet($offset){
returnisset($this->container[$offset])?$this->container[$offset]:null;
}
}
$obj=newobj();
var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj['two']="Avalue";
var_dump($obj['two']);
echo$obj['two'];
$obj[]='Append1';
$obj[]='Append2';
$obj[]='Append3';
var_dump($obj);
Countable
使对象能够计算属性classBasketimplementsCountable{
private$fruits=array('apple','banna','pear','orange','watermelon');
publicfunctioncount(){
returncount($this->fruits);
}
}
$basket=newBasket();
echocount($basket);