0

I've been looking at some examples of yield in PHP, trying to get a grasp of what situations one would use it in, and I began to notice that all of the examples I looked at had yield within a for(...) {} or foreach(...) {} statement.

Is there a way to use yield outside of a for?

user151841
  • 17,377
  • 29
  • 109
  • 171

1 Answers1

2

It doesn't require a loop. This works:

function foo() {
   yield 1;
   yield 2;
   yield 3;
} 

One reason to use this is to use it as a similar feature as 'await' in Javascript.

It's possible for example to build an async framework that uses yield for this purpose:

function foo() {
   $response = yield asyncHttpRequest('GET', 'http://blabla');
}

This specific example is fictional, but it's possible (and has been done).

I made such an async library. Docs here: https://sabre.io/event/coroutines/

There's better maintained/more popular libraries out there though.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • This is helpful, but I feel like I still don't understand all of what syntax exactly I can use to generate output with `yield`. Is it just sort of on a case-by-case bases? Like, you can use `for`, `foreach`, the imperative version you show, and the async style? – user151841 Oct 29 '20 at 19:07
  • 1
    I don't fully understand the question. Are you looking for a reason to use yield? Or do you have a real use-case in mind and hoping that yield can help with that? – Evert Oct 29 '20 at 19:15
  • I don't have a real use case-- what I mean is that, I feel like I don't have an intuitive understanding of `yield`. As a comparison, I generally know what a variable is, and where it can go in PHP syntax. There are "places" where it can belong and work. What I am saying is that I don't understand the "places" where `yield` can go. I listed two in my question, you showed me two more, but I don't understand the underlying logic of why `yield` can go there... does that make sense? Maybe this question is too broad for SO – user151841 Oct 29 '20 at 19:21
  • 2
    Probably too broad. `yield` is more generally a mechanism to pause functions and resume again later. – Evert Oct 29 '20 at 19:28
  • That's a very helpful insight. It seems to me now that it behaves like a `return` statement, which pauses execution within the scope where it's caled? – user151841 Nov 01 '20 at 00:09
  • 1
    Yeah that's exactly it =) – Evert Nov 01 '20 at 04:07