示例#1
0
/**
 * Implements the C# 'using' statement.
 *
 * Calls the supplied callable and, when done, disposes of the input object. This was
 * originally pulled from gonzalo123's 'using' repo @ https://github.com/gonzalo123/using
 *
 * @param  IDisposable $input    An instance of an IDisposable class.
 * @param  callable    $callback The callable function to use with the input class.
 */
function using(IDisposable $input, $callback = null)
{
    $disposer = function ($input) {
        $input->dispose();
    };
    try {
        \call_user_func($callback, $input);
        $disposer($input);
    } catch (\Exception $e) {
        $disposer($input);
        throw $e;
    }
}
示例#2
0
 /**
  * Invokes a function for a disposable object and keeps sure that the
  * IDisposable::dispose() method of it is called at the end of the invocation, even
  * if an exception is thrown. s. https://msdn.microsoft.com/en-us/library/yh598w02.aspx
  *
  * @param callable $func The function to invoke.
  * @param IDisposable $obj The disposable object.
  * @param mixed ...$arg One or more additional argument for $func.
  *
  * @return mixed The result of $func.
  *
  * @throws ArgumentException $func is no valid callable / lambda expression.
  * @throws ArgumentNullException $func is (null).
  */
 public static function using($func, IDisposable $obj = null)
 {
     if (null === $func) {
         throw new ArgumentNullException('func');
     }
     $func = static::asCallable($func);
     try {
         return \call_user_func_array($func, \array_merge([$obj], \array_slice(\func_get_args(), 2)));
     } finally {
         if (null !== $obj) {
             $obj->dispose();
         }
     }
 }