New PHP feature, comments please!
Posted: Thu Oct 30, 2008 3:39 pm
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
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