Page 1 of 1

New PHP feature, comments please!

Posted: Thu Oct 30, 2008 3:39 pm
by crazycoders
Hi, i'd like to suggest a few new magic methods regarding foreach or the domain of iteration. I don'T know where to post that anyway in the WWW so i'll post it here and see if anyone knows where to go next.

Methods:
__enum : Occurs when an object must be enumerated. When calling this function, it should return false if there are no array representation possible or return an array of elements to iterate
__next : In the event __enum failed, did not exist or returned false, __next is used to tell the object to push the internal enumeration pointer to the next item and returns true if an object exists, false if EOF
__current: Again, just like __next, this returns the current object from the enumeration.

So, in a Foreach, the magic methods would be called in this order

foreach($object as $value)
-> $object::__enum();

if __enum returned anything that is not enumerable (not an object or array) then foreach keeps $object as the enumeration source and loops:

1. __current: return the current pointer and foreach stores it as $value
2. __next: returns true if more items exist, false if nothing left
3. start over at __current until __next returns false;

Would this be an interresting feature?

I see a use for this because i do a lot of OOP in PHP and am forced to create a method that dumps my objects to an array manually when i want to iterate them such as:

foreach($object->dump() as $value){
...
}

Instead, if a magic method existed, it would be more logical and natural to implement enumerations this way.

Thanks
Math

Re: New PHP feature, comments please!

Posted: Thu Oct 30, 2008 3:47 pm
by s.dot
Something like object iterators ?

Re: New PHP feature, comments please!

Posted: Thu Oct 30, 2008 4:36 pm
by allspiritseve
scottayy wrote:Something like object iterators ?
I second that. Use the SPL Iterator interface.

Re: New PHP feature, comments please!

Posted: Thu Oct 30, 2008 8:13 pm
by crazycoders
Oh well, seems i didn't look long enough...

Re: New PHP feature, comments please!

Posted: Fri Oct 31, 2008 12:26 pm
by josh
the PHP documentation for the SPL sucks so I'm posting this
http://www.phpro.org/tutorials/Introduction-to-SPL.html

Re: New PHP feature, comments please!

Posted: Fri Oct 31, 2008 1:29 pm
by crazycoders
Thanks i'll look at that...