Skip to content

Instantly share code, notes, and snippets.

@bkrukowski
Last active October 3, 2019 07:58
Show Gist options
  • Save bkrukowski/f889fcacd2e8c6c396e1f9304102c171 to your computer and use it in GitHub Desktop.
Save bkrukowski/f889fcacd2e8c6c396e1f9304102c171 to your computer and use it in GitHub Desktop.
<?php
function defer(&$ctx, callable $callable): void
{
$ctx[] = new class($callable)
{
private $callable;
public function __construct(callable $callable)
{
$this->callable = $callable;
}
public function __destruct()
{
call_user_func($this->callable);
}
};
}
function sayHello(): void
{
defer($_, function () {
echo "defer1\n";
});
defer($_, function () {
echo "defer2\n";
});
echo "hello\n";
}
echo "before hello\n";
sayHello();
echo "after hello\n";
// Output:
//
// before hello
// hello
// defer1
// defer2
// after hello
class ValueObject
{
private $value;
public function getValue()
{
return $this->value;
}
public function setValue($value): void
{
$this->value = $value;
}
}
function throwException(ValueObject $v): void
{
defer($_, function () use ($v) {
$v->setValue('after exception');
});
$v->setValue('before exception');
throw new \Exception('My exception');
}
$value = new ValueObject();
try {
throwException($value);
} catch (\Exception $e) {
} finally {
echo $value->getValue(), "\n";
}
// Output:
//
// after exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment