PHP预定义接口概述
PHP语言内置了多个预定义接口,其中最为开发者频繁使用的包括IteratorAggregate(聚合式迭代器)、Countable、ArrayAccess以及Iterator这四个。下面将对它们进行逐一深入的解析。
IteratorAggregate接口详解
IteratorAggregate(聚合式迭代器)接口详解
复制代码 代码如下: IteratorAggregate extends Traversable { abstract public Traversable getIterator(void) }
该接口的核心功能是创建外部迭代器。具体而言,当使用foreach遍历未继承此接口的对象时,默认仅能遍历其所有public属性(需为public $var形式)。若类实现了IteratorAggregate,则foreach将调用类中实现的getIterator方法,并利用其返回的对象进行遍历。需注意,该方法必须返回一个Traversable对象或其子类实例,否则将触发异常。
//看个例子
class My{
private $_data = [
'a' => '燕睿涛',
'b' => 'yanruitao',
'c' => 'LULU',
];
public function getIterator()
{
return new ArrayIterator($this->_data);
}
}
$obj = new My;
foreach ($obj as $key => $value) {
echo "$key => $value\n";
}
//输出结果为空
class My implements IteratorAggregate {
private $_data = [
'a' => '燕睿涛',
'b' => 'yanruitao',
'c' => 'LULU',
];
public function getIterator()
{
return new ArrayIterator($this->_data);
}
}
$obj = new My;
foreach ($obj as $key => $value) {
echo "$key => $value\n";
}
//结果:
a => 燕睿涛
b => yanruitao
c => LULU
Countable接口详解
Countable接口 复制代码 代码如下: Countable { abstract public int count(void) }
此接口用于定义对象的数量统计行为。当对未实现Countable接口的对象调用count()函数时,默认返回值始终为1;而实现了该接口的对象,其count()方法的返回值即为最终结果。具体效果可参考以下示例:
class CountMe
{
protected $_myCount = 3;
public function count()
{
return $this->_myCount;
}
}
$countable = new CountMe();
echo count($countable);
//返回1
class CountMe implements Countable
{
protected $_myCount = 3;
public function count()
{
return $this->_myCount;
}
}
$countable = new CountMe();
echo count($countable);
//返回3
ArrayAccess接口
ArrayAccess {
abstract public boolean offsetExists(mixed $offset)
abstract public mixed offsetGet(mixed $offset)
public void offsetSet(mixed $offset, mixed $value)
public void offsetUnset(mixed $offset)
}
class CountMe
{
protected $_myCount = 3;
public function count()
{
return $this->_myCount;
}
}
$countable = new CountMe();
echo count($countable);
//返回1
class CountMe implements Countable
{
protected $_myCount = 3;
public function count()
{
return $this->_myCount;
}
}
$countable = new CountMe();
echo count($countable);
//返回3
ArrayAccess接口详解
ArrayAccess接口 复制代码 代码如下: ArrayAccess { abstract public boolean offsetExists(mixed $offset) abstract public mixed offsetGet(mixed $offset) public void offsetSet(mixed $offset, mixed $value) public void offsetUnset(mixed $offset) }
该接口旨在让对象能够以类似数组的方式进行访问。其原理是PHP在词法分析阶段,若检测到对象被以数组语法(如$obj['key'])操作,会检查该类是否实现了ArrayAccess接口。若已实现,则执行对应的set、unset、isset或get操作。这使得开发者可以在类内部维护一个数组结构,并提供标准的数组操作语义。示例如下:
class myObj
{
}
$obj = new myObj;
$obj['name'];
//Fatal error: Cannot use object of type myObj as array in
class myObj implements ArrayAccess
{
public function offsetSet($offset, $value)
{
echo "offsetSet : {$offset} => {$value}\n";
}
public function offsetExists($offset)
{
echo "offsetExists : {$offset}\n";
}
public function offsetUnset($offset)
{
echo "offsetUnset : {$offset}\n";
}
public function offsetGet($offset)
{
echo "offsetGet : {$offset}\n";
}
}
$obj = new myObj;
$obj[1] = '燕睿涛';
isset($obj['name']);
unset($obj['name']);
$obj['yrt'];
//输出结果:
offsetSet : 1 => 燕睿涛
offsetExists : name
offsetUnset : name
offsetGet : yrt
class myObj implements ArrayAccess
{
private $_data = [];
public function offsetSet($offset, $value)
{
$this->_data[$offset] = $value;
}
public function offsetExists($offset)
{
return isset($this->_data[$offset]);
}
public function offsetUnset($offset)
{
unset($this->_data[$offset]);
}
public function offsetGet($offset)
{
return $this->_data[$offset];
}
}
$obj = new myObj;
$obj['yrt'] = '燕睿涛';
var_dump($obj['yrt']);
var_dump(isset($obj['yrt']));
unset($obj['yrt']);
var_dump(isset($obj['yrt']));
var_dump($obj['yrt']);
//输出:
string(9) "燕睿涛"
bool(true)
bool(false)
Notice: Undefined index: yrt //最后一个会报出Notice
上述基于ArrayAccess的对象仅支持基本的存取操作,尚不支持遍历。若要结合之前的IteratorAggregate接口以实现foreach遍历,可进行如下组合:
class myObj implements ArrayAccess, IteratorAggregate
{
private $_data = [];
public function getIterator()
{
return new ArrayIterator($this->_data);
}
......
}
$obj = new myObj;
$obj['yrt'] = '燕睿涛';
$obj[1] = '燕睿涛';
$obj['name'] = '燕睿涛';
$obj['age'] = 23;
foreach ($obj as $key => $value) {
echo "{$key} => {$value}\n";
}
//输出:
yrt => 燕睿涛
1 => 燕睿涛
name => 燕睿涛
age => 23
Iterator接口详解
Iterator接口详解:
复制代码 代码如下: Iterator extends Traversable { abstract public mixed current(void) abstract public scalar key(void) abstract public void next(void) abstract public void rewind(void) abstract public boolean valid(void) }
官方文档描述该接口为“可在内部迭代自己的外部迭代器或类的接口”,这较为晦涩。实际上,它与IteratorAggregate类似,都用于实现迭代功能,区别在于Iterator是在类内部直接实现迭代逻辑,而非返回外部迭代器对象。具体实现见下例:
class myObj implements Iterator{
private $_data = [];
public function __construct(Array $arr)
{
$this->_data = $arr;
}
public function current()
{
return current($this->_data);
}
public function key()
{
return key($this->_data);
}
public function next()
{
next($this->_data);
}
public function rewind()
{
reset($this->_data);
}
public function valid()
{
return $this->key() !== NULL;
}
}
$t = [
'yrt' => '燕睿涛',
'name' => '燕睿涛',
false,
'燕睿涛'
];
$obj = new myObj($t);
foreach ($obj as $key => $value) {
echo "{$key} => ".var_export($value, true)."\n";
}
//输出:
yrt => '燕睿涛'
name => '燕睿涛'
0 => false
1 => '燕睿涛'
此例参考了鸟哥关于Iterator模式笔试题的文章。但需注意,原文章中valid()方法的判断逻辑存在瑕疵:当数据值本身为false时,可能导致迭代提前截断。
总结与应用建议
总结 尽管上述内容看似抽象,但其实际应用价值巨大。建议读者研读Yii2等主流框架的源码,其中大量运用了这些接口。深入阅读后,你会逐渐意识到它们在构建灵活、可扩展架构中的重要作用。
以上就是本文全部介绍,希望大家喜欢。