Reputation: 435
I am reading http://php.net/manual/en/class.iterator.php, but had a hard time to understand the Example #1 Basic usage. Questions:
var_dump(__METHOD__);
I know you can use variable here, eg: var_dump($count)
, but METHOD is not variable, or it is global variable/constant?
foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
if I change it to:
foreach($it as $key => $value) {
}
if I run the script, it can still show the outcome, why?
var_dump($key, $value);
the outcome is
int 0 string 'firstelement' (length=12)
int 1 string 'secondelement' (length=13) ...
why it is this result? foreach($it as $key => $value)
, $it is object, it is not $array, so how could this happen?
Upvotes: 4
Views: 733
Reputation: 4446
The Iterator
interface allows the class to behave like it was an array in the foreach
statement.
Because it's not an array, the class must know, how to behave in this situation. This is done by calling (by the foreach
, let's say for simplicity) some methods that are implemented from the Iterator
interface. As it's the interface requirements, all of the methods should be implemented, even if you're not going to use some of them, like retrieving the key.
In the methods you can type whatever you like, even something that does not makes sense in the foreach
loop (say you do not increase the counter $position
).
In the manual the var_dump()
s are used to show you which methods are called. The __METHOD__
pseudo-constant is a string that returns the current method's name. You should remove these lines, as they are given for the example purposes only.
Each of the methods from the Iterator
interface are public, so you can call them from any place in the code, but there is no need to call them in your program. In the foreach
loop they are called automatically so that's why your empty loop works.
Upvotes: 1