Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Created April 13, 2015 01:26
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 chrisguitarguy/d449a5506ef4dc23069e to your computer and use it in GitHub Desktop.
Save chrisguitarguy/d449a5506ef4dc23069e to your computer and use it in GitHub Desktop.
A *with* statement in PHP?
<?php
/*
Ideally this would be part of the language:
with (createAnObject() as $object) {
$object->doStuff();
}
This is just sugar for:
$object = createAnObject();
$object->enter();
try {
$object->doStuff();
} finally {
$object->leave();
}
This isn't as necessary in PHP which has destructors. If you absolutely need
some clean up to run for an object, it can go in `__destruct`
*/
interface ContextManager
{
public function enter();
public function leave();
}
final class ExampleContextManager implements ContextManager
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function enter()
{
echo 'Entering Context', PHP_EOL;
}
public function leave()
{
echo 'Leaving Context', PHP_EOL;
}
public function getName()
{
return $this->name;
}
}
function with(ContextManager $context, \Closure $callback)
{
$context->enter();
try {
call_user_func($callback->bindTo($context));
} finally {
$context->leave();
}
}
with(new ExampleContextManager('Test1'), function () {
echo 'Indside Context: ', $this->getName(), PHP_EOL;
});
with(new ExampleContextManager('Test1'), function () {
throw new \Exception(sprintf('Oops! %s', $this->getName()));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment