Skip to content

Instantly share code, notes, and snippets.

@iansltx iansltx/With.php
Created Feb 27, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.