介绍
ArrayAccess接口是PHP5中新添加的一个接口,其功能是使类可以像PHP中的数组一样操作。有点类似于.net平台的index操作。其接口很简单,就四个函数:
- interface ArrayAccess
- {
- public function offsetGet($index);
- public function offsetSet($index, $value);
- public function offsetExists($index);
- public function offsetUnset($index);
- }
offsetGet是数组的取值操作;offsetSet是数组的赋值操作;offsetExists判断值是否存在,用于isset语句;offsetUnset删除操作,用于unset语句。
实现
- class Book1 implements ArrayAccess
- {
- private $name;
- private $author;
- public function offsetGet($index)
- { return $this-<$index[$index]; }
- public function offsetSet($index, $value)
- { $this-<$index = $value; }
- public function offsetExists($index)
- { return isset($this-<$index); }
- public function offsetUnset($index)
- { unset($this-<$index); }
- }
- $book = new Book1();
- $book['name'] = 'PHP';
- $book['author'] = 'caixw';
- print_r($book);
- class Book2 implements ArrayAccess
- {
- private $_book;
- public function __construct(array &$book)
- { $this-<_book = $book; }
- public function offsetGet($index)
- { return $this-<_book[$index]; }
- public function offsetSet($index, $value)
- { throw new exception('不允许修改!'); }
- public function offsetExists($index)
- { return isset($this-<_book[$index]); }
- public function offsetUnset($index)
- {}
- }
- $books = array();
- $rows = mysql_query("SELECT * FROM books")-<fetchAll();
- foreach($rows as $row)
- {
- $books[] = new Book2($row);
- }
- $books[1]['author'] = 'author'; // 抛出异常
- unset($books[1]['author']); // 不会发生任何操作
- print_r($book);
ArrayObject
- class Book3 extends ArrayObject
- {
- public function __construct(array &$array)
- {
- // todo
- parent::__construct($array);
- }
- public function offsetSet($index, $value)
- { throw new exception(''); }
- public function offsetUnset($index)
- {}
- }

浙公网安备 33010602011771号