php对象怎么循环,php中对object对象使用foreach循环操作

本文探讨了PHP中如何通过实现Iterator接口使对象支持循环操作。对比了普通对象与实现了Iterator接口的对象在循环时的不同表现,并详细解释了Iterator接口的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

抛出疑问

php的对象是可以使用诸如foreach进行循环的。对象的循环,其实就是对像的开放属性进行的循环。但是在某些框架中,比如laravel中的对象循环,我们发现它并不是对属性进行遍历。

普通对象:

class abc{

public $a = ‘a‘;

public $b = ‘b‘;

protected $c = ‘c‘;

private $d = ‘d‘;

public function index(){

return ‘func‘;

}

}

$abc = new abc();

foreach($abc as $item){

dump($item);

}

打印结果如下:

"a"

"b"

laravel集合:

这是使用laravel查询的分页对象

$list = Article::paginate(15);

Illuminate\Pagination\LengthAwarePaginator {#504 ▼

#total: 2

#lastPage: 1

#items: Illuminate\Database\Eloquent\Collection {#510 ▼

#items: array:2 [▼

0 => App\Models\Article {#505 ?}

1 => App\Models\Article {#497 ?}

]

}

#perPage: 15

#currentPage: 1

#path: "http://hxsen.houxin.com/category/2"

#query: []

#fragment: null

#pageName: "page"

+onEachSide: 3

#options: array:2 [?]

}

提示

# 表示保护属性

+ 表示公开属性

- 表示私有属性

但是,对该循环的结果分析发现,它遍历的并不该对象本身。而是私有的#items属性下面的集合。

问题探究

查阅文档,我们发现最早php5.0的时候就已经支持了一个叫Iterator接口,并提供了一系列的方法供实现该接口的类定义。

interface Iterator extends Traversable {

public function current();

public function next();

public function key();

public function valid();

public function rewind();

}

说明:

current:返回当前元素

next:向前移动到下一个元素

key: 返回当前元素的键

valid:检查当前位置是否有效

rewind:将迭代器倒回到第一个元素

问题解决

现在修改一下类,实现Iterator方法

class xyz implements Iterator{

private $_items = array(1,2,3,4,5,6,7);

public $a = ‘a‘;

public $b = ‘b‘;

protected $c = ‘c‘;

private $d = ‘d‘;

public function index(){

return ‘func‘;

}

// Rewind the Iterator to the first element

public function rewind() { reset($this->_items); }

// Return the current element

public function current() { return current($this->_items); }

// Return the key of the current element

public function key() { return key($this->_items); }

// Move forward to next element

public function next() { return next($this->_items); }

// Checks if current position is valid

public function valid() { return ( $this->current() !== false ); }

}

上面的类中的_items是我们自定义的数组集合。

此时,我们再次对它进行循环

$xyz = new xyz();

foreach($xyz as $value){

dump($value);

}

现在,打印的结果变成了我们的那个_items数组的元素了。同时,内部的公开属性,也不在循环之列了。

1

2

3

4

5

6

7

总结说明

PHP中Interator接口的作用,就是允许对象以自己的方式迭代内部的数据,从而使它可以被循环访问

当循环执行valid返回false时,循环就结束了。

原文:https://www.cnblogs.com/hxsen/p/12704049.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值