Php Iterator foreach on object properties

Given a class

class Obj {  public $a =1;  public $b = 2; } 

and script like

$obj = new Obj();  foreach($obj as $key => $value)     echo $key, $value; 

I can easily output what’s inside the object, but why doesn’t it work if the class is like that

class SomeClass() implements Iterator { ... } 

Is Iterator interface forbidden me to do foreach outside and forcing me to use its abstract functions for this purpose? Tyvm.

Add Comment
1 Answer(s)

When a class implements Iterator, foreach iterates over the elements of the collection that it represents. When the class doesn’t implement Iterator, it falls back to iterating over the properties.

If you want to iterate over the properties of this class, convert the object to an array:

foreach ((array)$obj as $key => $value)     echo $key, $value; 
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.