happy cat image

Start Web Coding

Your First step toward web coding,
Start Web Coding

change UI

Generator - yield

Earlier we learned about functions.
A function ends its life when it encounters a return statement.
This time, we will learn how to use a slightly different type of function.
It's called a generator.
Generators have a function that pauses while the function is running.
And when you resume a paused function, it resumes where it left off.
To use a generator, use the yield keyword.

How to Use the Generator Yield Keyword

function function name() {

    echo "Operation 1 <br>";
    echo "Operation 2 <br>";

    yield "generator 1";

    echo "Operation 3 <br>";
    echo "Operation 4 <br>";

    yield "generator 2";

    echo "Operation 5 <br>";
    echo "Operation 6 <br>";
}

When calling the generator, the function name() is not called like this.
It is called through the foreach statement.

function function name() {

    echo "Operation 1 <br>";
    echo "Operation 2 <br>";

    yield "generator 1";

    echo "Operation 3 <br>";
    echo "Operation 4 <br>";

    yield "generator 2";

    echo "Operation 5 <br>";
    echo "Operation 6 <br>";
}

foreach(function name() as $value){
    echo $value;
}

Then let's see through the code.
If you call the generator through the foreach statement, exit the function through the yield, and call the generator again, it will be executed again after the yield statement that exited.

<?php
    function call() {

        echo "work 1 <br>";
        echo "work 2 <br>";

        yield "generator 1 --<br>";

        echo "work 3 <br>";
        echo "work 4 <br>";

        yield "generator 2 --<br>";

        echo "work 5 <br>";
        echo "work 6 <br>";
    }

    foreach(call() as $c){
	    echo $c;
	}
?>

The generator is also a function, so when the return statement is encountered, the function does not work.

<?php
    function call() {

        echo "work 1 <br>";
        echo "work 2 <br>";

        yield "generator 1 --<br>";

        return;

        echo "work 3 <br>";
        echo "work 4 <br>";

        yield "generator 2 --<br>";

        echo "work 5 <br>";
        echo "work 6 <br>";
    }

    foreach(call() as $c){
	    echo $c;
	}
?>

Yes what do you use this way. We have learned about the yield statement of generators.

강좌로 돌아가기