PHP-迭代器与序列化

来源:互联网 发布:网络客服主管计划 编辑:程序博客网 时间:2024/06/05 21:17

一、迭代器,方便foreach循环

有2种迭代器的接口

  1. Iterator,抽象方法如下,implements的时候,必须都要实现
  • current->返回当前元素的值
  • key->返回当前元素的键
  • next->把key自增1
  • rewind->调转到第一个元素,即把key初始化为0
  • valid->验证当前的元素是否存在

2.IteratorAggregate

  • 只有一个方法,getIterator,获得一个外部迭代器

二、数组式访问,可以像使用数组一样,[ ]来使用这个类

1、ArrayAccess

class  obj  implements  ArrayAccess  {    private  $container  = array();    public function  __construct () {         $this -> container  = array(             "one"    =>  1 ,             "two"    =>  2 ,             "three"  =>  3 ,        );    }    public function  offsetSet ( $offset ,  $value ) {        if ( is_null ( $offset )) {             $this -> container [] =  $value ;        } else {             $this -> container [ $offset ] =  $value ;        }    }    public function  offsetExists ( $offset ) {        return isset( $this -> container [ $offset ]);    }    public function  offsetUnset ( $offset ) {        unset( $this -> container [ $offset ]);    }    public function  offsetGet ( $offset ) {        return isset( $this -> container [ $offset ]) ?  $this -> container [ $offset ] :  null ;    }}

三、序列化与反序列化

serialize把数组变成字符串

unserialize把字符串变成数组


0 0
原创粉丝点击