bool spl_autoload_register ([ callback $autoload_function ] )
踢走PHP固有的__autoload(),如果你有自己好的自动加载函数,你行上你啊!
__autoload()本身其实挺烦的,首先它没有返回值,也就是如果你在里面用的是include的话,说不定你都不知道你有没有成功加载到数据。
另外,如果你是想自己写个框架,在自动加载函数里面希望调用基类的方法?可以啊,不过私有成员就别想了。现在有了spl_autoload_register,你可以将你自定义的函数或者类方法作为自动加载函数了。而且还有返回值,就算里面用了include也可以知道类是否加载成功。
另外一大堆迭代器接口也是SPL的一大重要内容,最近折腾了一下,写了个数据类,不过总感觉有些啥问题,觉得不合理就留言指正吧。
class dataclass implements ArrayAccess,RecursiveIterator { protected $_data; protected $_position = 0; protected $_keylist = array(); public function __construct($data = null) { $this->_data = new stdClass(); if (is_array($data)) { foreach ($data as $key => $val) { $this->offsetSet($key, $val); } } } public function offsetExists($offset) { return property_exists($this->_data, $offset); } public function offsetGet($offset) { //if (is_array($this->_data->{$offset})) { //return new dataclass ($this->_data->{$offset}); //} else { return $this->_data->{$offset}; //} } public function offsetUnset($offset) { $key = array_search($offset, $this->_keylist); unset ($this->_keylist[$key]); unset ($this->_data->{$offset}); } public function offsetSet($offset,$value) { if (!in_array($offset, $this->_keylist)) { $this->_keylist[] = $offset; } $this->_data->{$offset} = $value; } public function current() { $key = $this->keyName(); return $this->_data->{$key}; } public function key() { return $this->_position; } public function keyName() { return $this->_keylist[$this->_position]; } public function next() { ++$this->_position; } public function rewind() { $this->_position = 0; } public function valid() { return $this->_position < count($this->_keylist); } public function getChildren() { return new dataclass($this->current()); } public function hasChildren() { $current = $this->current(); return !empty($current) && is_array($current); } }