Reputation: 3441
It just occured to me that I can loop through a $collections object returned from Model::where(), even though its not an array. Doing some googling shows looping through an object goes through all of the object's parameters, which isn't what happens to the Collection object. How exactly do they do this in Laravel? What is this black magic?
I guess maybe more generally, how can you set an object up that it is compatible inside foreach()?
Upvotes: 0
Views: 695
Reputation: 24101
There is of course no magic involved here, you can do it yourself in your classes. The only thing you have to do, is to implement the IteratorAggregate interface, from then on your class can be used in a foreach loop.
Upvotes: 1
Reputation: 213
If your object implements a specific interface or extends a specific class, PHP knows how to iterate it: http://www.php.net//manual/en/language.oop5.iterations.php
Upvotes: 3