前言
前言
默认遍历行为与局限性
在PHP中,使用foreach遍历对象时,其行为与遍历数组类似,但键名对应对象的属性名,值对应属性值。需要注意的是,当在类外部进行遍历时,仅能访问到public修饰的属性,因为protected和private修饰的属性具有封装性,在类外部不可见。
Iterator接口实现原理
class HardDiskDrive {
public $brand;
public $color;
public $cpu;
public $workState;
protected $memory;
protected $hardDisk;
private $price;
public function __construct($brand, $color, $cpu, $workState, $memory, $hardDisk, $price) {
$this->brand = $brand;
$this->color = $color;
$this->cpu = $cpu;
$this->workState = $workState;
$this->memory = $memory;
$this->hardDisk = $hardDisk;
$this->price = $price;
}
}
$hardDiskDrive = new HardDiskDrive('希捷', 'silver', 'tencent', 'well', '1T', 'hard', '$456');
foreach ($hardDiskDrive as $property => $value) {
var_dump($property, $value);
echo '
';
}
输出结果为:
string(5) "brand" string(6) "希捷" string(5) "color" string(6) "silver" string(3) "cpu" string(7) "tencent" string(9) "workState" string(4) "well"
从上述输出结果可以看出,默认的遍历机制无法获取受保护或私有的属性信息。
实现全属性遍历的方法
若希望遍历对象的所有属性(包括protected和private),则需要自定义类的行为,使其支持迭代功能。这要求类实现Iterator接口,从而为foreach提供必要的迭代控制逻辑。
该接口定义了实现foreach所需的标准操作方法。foreach的执行流程涉及多个关键步骤,具体逻辑可参考下图:

观察流程图可知,foreach遍历过程包含5个关键步骤。
Iterator接口所要求的5个方法,正是为了协助foreach完成这5个关键步骤而设计的。
当foreach去遍历对象时, 如果发现对象实现了Iterator接口, 则执行以上5个步骤时, 不是foreach的默认行为, 而是调用对象的对应方法即可:

示例代码:
class Team implements Iterator {
//private $name = 'itbsl';
//private $age = 25;
//private $hobby = 'fishing';
private $info = ['itbsl', 25, 'fishing'];
public function rewind()
{
reset($this->info); //重置数组指针
}
public function valid()
{
//如果为null,表示没有元素,返回false
//如果不为null,返回true
return !is_null(key($this->info));
}
public function current()
{
return current($this->info);
}
public function key()
{
return key($this->info);
}
public function next()
{
return next($this->info);
}
}
$team = new Team();
foreach ($team as $property => $value) {
var_dump($property, $value);
echo '
';
}
总结
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。