<?php
/**
* These functions pair up nicely with generators, to hide away
* all the messy file handlers (a bit like python's with blocks)
* remove the echos they are just to demo how the generator
* works with the foreach loop.
*
* @param string $filepath
* @return Generator<string>
*/
function generateFiles(string $filepath): Generator
{
echo "opening handle" . PHP_EOL;
$handle = opendir($filepath);
// looks more complex than needed but the docs says the type check is important
// https://www.php.net/manual/en/function.readdir.php
try {
while (false !== ($entry = readdir($handle))) {
yield $entry;
}
} finally {
closedir($handle);
echo "closed handle" . PHP_EOL;
}
}
foreach (generateFiles('.') as $file) {
echo $file . PHP_EOL;
}