Jump to content

better way to iterate?


andychurchill

Recommended Posts

I took this base collection example from here: http://www.devshed.com/c/a/PHP/Collections-and-Sorting/2/

 

interface ICollection

{

    public function Get($i);

    public function Append($object);

    public function Sort();

}

 

interface ISortable

{

    public function GetSortKey();

}

 

abstract class Collection implements ICollection

{

    protected $data; 

 

    public function __construct()

    {

          $this->data = new ArrayObject();

    }   

 

    public function Get($i)

    {

          return $this->data[$i];

    }   

 

    public function Append($object)

    {

          $this->data->Append($object);

    }   

 

    public function Sort()

    {

    }

}

 

I then added a new function to the abstract collection class

 

function Count()

{

        return $this->data->count() - 1;

}

 

so that in my code I can now do this, where $someCollection is a collection of objects that inherits from this base Collection class.

 

$maxcount = $someCollection->Count();

 

for ($counter = 0; $counter <= $maxcount; $counter += 1) {

    print_r($someCollection->Get($counter));

}

 

which works, but my question is, is there a better way to modify the collection so that I can do something like this, which from what I can tell doesn't work currently as I've not provided this new class with any form of iteration?

 

foreach($someCollection as $item) {

    print_r($item);

}

 

I'm new btw, just learning the ropes :)

 

 

Link to comment
https://forums.phpfreaks.com/topic/168869-better-way-to-iterate/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.