PHP coroutine keyword yield learning

php5.5 added yield, which is actually a creator syntax.

There are many related introductions, see the code here
    function fun1($action){
        while(1){
            $ num2 = rand (1000.9999);
            $stored = $action->send( $num2 ) ;
            echo "[fun1:{$stored} ]<br>";
            if($stored ==5){
                break;
            }
        }
    }

    function fun2(){
        $r=0;
        while(1){
            $num=(yield $r);
            echo $num."<br>";
            $r++;
        }
    }
    
    $gen = fun2();
    $fun1($gen);
    


Results display
6593
[fun1:1 ]
1600
[fun1:2 ]
7428
[fun1:3 ]
6764
[fun1:4 ]
3670
[fun1:5 ]


fun2() gets a creator object.
A creator object can iterate over values ​​like an array, but here the send syntax is used.
The send syntax can pass parameters between two functions. Here fun1 passes random numbers to fun2 for display, and fun2 returns the number of times to fun1. This is the ingeniousness of the creator.

Explain the process:
After $num2 is executed, execute the send statement.
Entering fun2, the send statement will look for the current yield, execute it, and then return in the next yield. The key point here is to skip the first yield and return in the second yield. That's the gist.
Therefore, when returning from send, $r++ has been executed once, and then the current $r is returned in yield, which is 1,
so fun1:1 is displayed.
When send is executed again, the creator continues execution from the last breakpoint, and the send statement is an assignment statement, and then 2.
Keep going.


Point 1:
yield can return, and can be assigned by an external send command, and then passed to the variable on the left side of the equal sign. In other words, it is also an expression itself, and its value is the value passed by the external send.
Point 2:
The send syntax finds the current yield and returns at the next yield, or at the end of the creator's function. So it looks like the first yield is skipped.

However, this is all synchronous code, so I don't see any use for now.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326314902&siteId=291194637