PHP迭代器不能通过引用与foreach一起使用 [英] PHP An iterator cannot be used with foreach by reference

查看:189
本文介绍了PHP迭代器不能通过引用与foreach一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现Iterator并保存2个数组的对象:条目"和页面".每当我遍历此对象时,我都想修改entrys数组,但是会收到错误An iterator cannot be used with foreach by reference,该错误在

I have an object that implements Iterator and holds 2 arrays: "entries" and "pages". Whenever I loop through this object, I want to modify the entries array but I get the error An iterator cannot be used with foreach by reference which I see started in PHP 5.2.

我的问题是,如何在使用foreach的同时使用Iterator类更改循环对象的值?

My question is, how can I use the Iterator class to change the value of the looped object while using foreach on it?

我的代码:

//$flavors = instance of this class:
class PaginatedResultSet implements \Iterator {
    private $position = 0;

    public $entries = array();
    public $pages = array();

    //...Iterator methods...
}

//looping
//throws error here
foreach ($flavors as &$flavor) {
    $flavor = $flavor->stdClassForApi();
}

这样做的原因是有时$flavors不会 成为我的类的实例,而只是一个简单的数组.我希望能够轻松修改此数组,而不管其类型是什么.

The reason for this is that sometimes $flavors will not be a an instance of my class and instead will just be a simple array. I want to be able to modify this array easily regardless of the type it is.

推荐答案

我刚刚尝试创建一个迭代器,该迭代器使用:

I just tried creating an iterator which used:

public function &current() {
    $element = &$this->array[$this->position];
    return $element;
}

但是那还是行不通的.

我最好推荐的是您实现\ArrayAccess,它将允许您执行以下操作:

The best I can recommend is that you implement \ArrayAccess, which will allow you to do this:

foreach ($flavors as $key => $flavor) {
    $flavors[$key] = $flavor->stdClassForApi();
}

使用生成器:

根据生成器上的Marks注释进行更新,以下内容将使您可以迭代结果,而无需实现\Iterator\ArrayAccess.

Updating based on Marks comment on generators, the following will allow you to iterate over the results without needing to implement \Iterator or \ArrayAccess.

class PaginatedResultSet {
    public $entries = array();

    public function &iterate()
    {
        foreach ($this->entries as &$v) {
            yield $v;
        }
    }
}

$flavors = new PaginatedResultSet(/* args */);

foreach ($flavors->iterate() as &$flavor) {
    $flavor = $flavor->stdClassForApi();
}

这是PHP 5.5中可用的功能.

This is a feature available in PHP 5.5.

这篇关于PHP迭代器不能通过引用与foreach一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆