Skip to content

Instantly share code, notes, and snippets.

@iansltx
Created February 27, 2019 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iansltx/c0d8a4344b5dbbfc6efffab184238dfb to your computer and use it in GitHub Desktop.
Save iansltx/c0d8a4344b5dbbfc6efffab184238dfb to your computer and use it in GitHub Desktop.
Simulating Python's With keyword with foreach and a trait in PHP
<?php // Pretty sure this doesn't clean up on exceptions, so keep that in mind
trait With
{
abstract protected function enter(...$args);
protected function exit($built, ...$initArgs)
{
// override this if needed
}
public function __invoke(...$args) : \Generator
{
$built = $this->enter(...$args);
yield $built;
$this->exit($built, ...$args);
unset($built);
}
}
class FilePointer
{
use With;
protected function enter($path, $mode)
{
return fopen($path, $mode);
}
protected function exit($fp, ...$args)
{
fclose($fp);
}
}
foreach ((new FilePointer)('test.txt', 'w') as $fp) {
fwrite($fp, "Hello World\n");
var_dump($fp);
}
var_dump($fp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment