Md. Mahmudul Islam
Md. Mahmudul Islam

Reputation: 11

Getting PHP Recoverable fatal error: Object of class Generator could not be converted to string in PHP Iterable

I am new in php. Running this php script getting errors: It shows this message :-

PHP Recoverable fatal error: Object of class Generator could not be converted to string in index.php on line 19

<?php

 class Example {

     function bar(): iterable{
         return [1, 2, 3];
     }


     function gen(): iterable {
         yield 1;
         yield 2;
         yield 3;
     }

}
$obj=new Example();

print $obj->gen();

print $obj->bar();

Upvotes: 1

Views: 7129

Answers (1)

Alex Howansky
Alex Howansky

Reputation: 53591

You're trying to print $obj->gen(), which is an iterable. Think about what it means to print an iterable, what would it look like? If you want to debug it, just to see what's in it, you can use print_r(). Otherwise, iterables are made to be looped over:

foreach ($obj->gen() as $item) {
    echo $item;
}

Note, you can also define your class so that it implements IteratorAggregate, then change the name of your method to getIterator():

 class Example implements IteratorAggregate {
    public function getIterator() {
        yield 1;
        yield 2;
        yield 3;
    }
 }

Then you can iterate directly over the object itself:

foreach ($obj as $item) {
}

Or even this:

foreach (new Example() as $item) {
}

Upvotes: 3

Related Questions