andychurchill Posted August 4, 2009 Share Posted August 4, 2009 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 More sharing options...
trq Posted August 5, 2009 Share Posted August 5, 2009 You might want to take a look at the spl array object. See spl. Link to comment https://forums.phpfreaks.com/topic/168869-better-way-to-iterate/#findComment-891120 Share on other sites More sharing options...
trq Posted August 5, 2009 Share Posted August 5, 2009 Sorry, didn't see you where already using it. Your Collection class should probably extend it. Link to comment https://forums.phpfreaks.com/topic/168869-better-way-to-iterate/#findComment-891121 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.