简体   繁体   English

从对象迭代数组

[英]Iterate over array from object

I want to perform some magic so that when I try to iterate over an object I will actually iterate over an array from within the object. 我想执行一些魔术操作,以便当我尝试遍历对象时,实际上将遍历该对象内部的数组。 Something like a getter for loops. 类似于循环的吸气剂。

class A {
    protected $array = [1,2,3];

    public function __foriteration() {
        return $this->array;
    }
}

$a = new A;

foreach($a as $value) {
   echo $value;
}

// output should be "123"

Not even sure that this is possible but I suspect I should be using ArrayObject but it is not very straightforward for me, I can't figure out how to make it do this. 甚至不确定这是否可行,但我怀疑我应该使用ArrayObject但这对我来说不是很简单,我不知道如何使它执行此操作。

Please note : I could define a getter method and loop over $a->getArray() but that is not what I want to do. 请注意 :我可以定义一个getter方法并在$a->getArray()循环,但这不是我想要的。 Thank you. 谢谢。

You can implement the Iterator interface . 您可以实现Iterator接口 To do that, you need to implement a couple of methods in your object, which you can redirect to your array: 为此,您需要在对象中实现几个方法,您可以将其重定向到数组:

<?php

class A implements Iterator {
    protected $array = [1,2,3];

    public function __foriteration() {
        return $this->array;
    }

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

    public function current()
    {
        $value = current($this->array);
        return $value;
    }

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

    public function next() 
    {
        $value = next($this->array);
        return $value;
    }

    public function valid()
    {
        $key = key($this->array);
        return $key !== null && $key !== false;
    }    
}

$a = new A;

foreach($a as $value) {
   echo $value;
}

Of course you can implement your own method of keeping track of the 'current' item, but since an array does that already, it's as easy to let it do it for you, and methods like rewind just call array functions. 当然,您可以实现自己的方法来跟踪“当前”项,但是由于数组已经做到了,因此让它轻松为您完成, rewind方法只需调用数组函数即可。

Rather than writing all the boilerplate to make this an iterable object, you could use a generator: 您可以使用生成器,而不是编写所有样板使其成为可迭代的对象:

class A {
    protected $array = [1,2,3];

    public function __foriteration() {
        foreach($this->array as $value) {
            yield $value;
        }
    }
}

$a = new A;

foreach($a->__foriteration() as $value) {
   echo $value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM