Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cannot Yield And Never

<?php

function naturalIntegers() {
    $i = 0;
    while (true) {
        yield $i++;
    }
}

foreach(naturalIntegers() as $i) {
    if ($i > 10) {
        break;
    }
    print $i.PHP_EOL;
}

print "finished
";

Never, as a return type, mentions that the method will never return. This means that it either calls exit(), throws an exception, or is an infinite loop.

Infinite loop escaped my radar until I realized it is a good way to characterize the loop in an explicit way: put any explicit loop in a never method and know before hand of the implications.

Sadly, infinite loop work very well with Yield and yield from, but such methods must be typed with Generator. Too bad.

See Also

PHP Features

Last updated: 09 November 2026