这篇文章主要给大家介绍了关于PHP中Iterator迭代对象属性的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用PHP具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
前言
foreach用法和之前的数组遍历是一样的,只不过这里遍历的key是属性名,value是属性值。在类外部遍历时,只能遍历到public属性的,因为其它的都是受保护的,类外部不可见。
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 '<br>';
}
输出结果为:
string(5) "brand" string(6) "希捷"
string(5) "color" string(6) "silver"
string(3) "cpu" string(7) "tencent"
string(9) "workState" string(4) "well"
通过输出结果我们也可以看得出来常规遍历是无法访问受保护的属性的。
如果我们想遍历出对象的所有属性,就需要控制foreach的行为,就需要给类对象,提供更多的功能,需要继承自Iterator的接口:
该接口,实现了foreach需要的每个操作。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 '<br>';
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对编程学习网的支持。
本文标题为:PHP中的Iterator迭代对象属性详解
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
- PHP仿tp实现mvc框架基本设计思路与实现方法分析 2022-10-18
- Laravel balde模板文件中判断数据为空方法 2023-08-30
- 用nohup命令实现PHP的多进程 2023-09-02
- laravel通用化的CURD的实现 2023-03-17
- PHP中PDO事务处理操作示例 2022-10-15
- windows下9款一键快速搭建PHP本地运行环境的好工具(含php7.0环境) 2023-09-02
- PHP简单实现二维数组的矩阵转置操作示例 2022-10-02
- laravel实现按月或天或小时统计mysql数据的方法 2023-02-22
- PHP实现微信支付(jsapi支付)流程步骤详解 2022-10-09
- php微信公众号开发之秒杀 2022-11-23