Created
February 27, 2019 07:24
-
-
Save iansltx/c0d8a4344b5dbbfc6efffab184238dfb to your computer and use it in GitHub Desktop.
Simulating Python's With keyword with foreach and a trait in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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