caixw.com

把时髦的技术挂在嘴边,还不如把过时的技术记在心里!

ArrayAccess接口介绍

caixw

介绍

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语句。

实现

下面我们用一个具体的类,看看ArrayAccess是如何使用的:

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

ArrayObject是一个已经实现了ArrayAccess接口的类,类似于上面Book2这个类,当然它没有限制写操作。所以很多时候我们可以直接从ArrayObject类继续,而不是从头开始实现ArrayAccess,所以Book2可以直接从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)
    {}
}

评论(0)

添加评论

验证码

还没有漂亮的个人头像吧?

Gravatar申请一个吧!

没有中文输入法吗?试试这个!

  accesskey="enter"