useless-stuff
2/16/2016 - 10:48 AM

PHP - LimitIterator

PHP - LimitIterator

<?php
/**
 * Class RandomObject
 */
class RandomObject
{

    protected $value;

    /**
     * RandomObject constructor
     */
    public function __construct()
    {

        $this->value = rand(0, 1000);
    }

    /**
     * @return int
     */
    public function getValue()
    {

        return $this->value;
    }

    /**
     * @param int $value
     */
    public function setValue($value)
    {

        $this->value = $value;
    }
}

// Generate random data
$objectsCollection = new ArrayIterator();
for ($i = 1; $i < 100; $i++) {
    $objectsCollection->append(new RandomObject());
}


$limitIterator = new LimitIterator($objectsCollection, 20, 5);
foreach ($limitIterator as $iterator) {
    print_r($iterator);
}

// Output
/*
[
    {
        value:protected: "450"
    },
    {
        value:protected: "639"
    },
    {
        value:protected: "105"
    },
    {
        value:protected: "852"
    },
    {
        value:protected: "391"
    }
]
*/