php

位置:IT落伍者 >> php >> 浏览文章

php重载数组操作符


发布日期:2018年02月02日
 
php重载数组操作符

在php中提供了许多接口用于实现一些很特定的功能比如你想把一个对象当作array使用时只需要实现ArrayAccess接口当你想要foreach中能够使用一个对象时只需要实现Iterator接口下面给一个例子出来

class BtstoreRoot{/** * 根结点 * @var BtstoreElement */static $root;}class BtstoreElement implements ArrayAccess Iterator{/** * 当前所代表的目录 * @var string */private $dataDir;/** * 当前所代表的数据 * @var array */private $arrData;/** * 构造函数 * @param string $dataDir * @param array $arrData */function __construct($dataDir $arrData){$this>dataDir = ;$this>arrData = array ();if (! empty ( $dataDir ) && is_dir ( $dataDir )){$this>dataDir = $dataDir;}if (! empty ( $arrData )){$this>arrData = $arrData;}}function __get($key){if (isset ( $this>arrData [$key] )){$data = $this>arrData [$key];if (is_array ( $data ) && ! is_object ( $data )){$data = new BtstoreElement ( $data );}return $data;}if (! empty ( $this>dataDir )){$path = $this>dataDir / $key;if (is_dir ( $path )){$data = new BtstoreElement ( $path null );$this>arrData [$key] = $data;return $data;}if (is_file ( $path )){$content = file_get_contents ( $path );$arrData = unserialize ( $content );$data = new BtstoreElement ( $arrData );$this>arrData [$key] = $data;return $data;}}trigger_error ( "undefined index:$key" );}function __isset($key){if (isset ( $this>arrData [$key] )){return true;}if (file_exists ( $this>dataDir / $key )){return true;}return false;}function toArray(){return $this>arrData;}/* (nonPHPdoc) * @see ArrayAccess::offsetExists() */public function offsetExists($offset){return $this>__isset ( $offset );}/* (nonPHPdoc) * @see ArrayAccess::offsetGet() */public function offsetGet($offset){return $this>__get ( $offset );}/* (nonPHPdoc) * @see ArrayAccess::offsetSet() */public function offsetSet($offset $value){trigger_error ( offsetSet not implemented by BtstoreElement );}/* (nonPHPdoc) * @see ArrayAccess::offsetUnset() */public function offsetUnset($offset){trigger_error ( offsetUnset not implemented by BtstoreElement );}/* (nonPHPdoc) * @see Iterator::current() */public function current(){return current ( $this>arrData );}/* (nonPHPdoc) * @see Iterator::next() */public function next(){return next ( $this>arrData );}/* (nonPHPdoc) * @see Iterator::key() */public function key(){return key ( $this>arrData );}/* (nonPHPdoc) * @see Iterator::valid() */public function valid(){$data = current ( $this>arrData );return ! empty ( $data );}/* (nonPHPdoc) * @see Iterator::rewind() */public function rewind(){reset ( $this>arrData );}}/** * 获取一个BtstoreElement对象 * @return BtstoreElement */function btstore_get(){if (empty ( BtstoreRoot::$root )){BtstoreRoot::$root = new BtstoreElement ( ScriptConf::BTSTORE_ROOT null );}return BtstoreRoot::$root;}

               

上一篇:在windows平台上构建自己的PHP实现方法(仅适用于php5.2)

下一篇:浅析php插件 Simple HTML DOM 用DOM方式处理HTML