Ehsan Bagherzadegan
Back to articles
6 min read

PHP Context Managers v2: Automatic Cleanup with the using Expression

The new PHP RFC introduces a generator-based `using` expression for PHP 8.7 — bringing automatic setup-and-teardown blocks for transactions, locks, file handles, and timed operations.

PHP's upcoming Context Managers v2 RFC — announced on the internals mailing list on November 5, 2026 — proposes a using expression that brings automatic setup-and-cleanup blocks to the language. If accepted, it will land in PHP 8.7 and change how we write code that acquires resources, starts transactions, measures time, or needs any kind of scoped teardown logic.

Why this matters

Every PHP developer writes cleanup code: closing file handles, rolling back database transactions, releasing locks, restoring global state. Today we do it with try/finally, destructors, or register_shutdown_function. All of them have friction:

  • try/finally is verbose and separates setup from cleanup by dozens of lines.
  • Destructors run at an unpredictable time (end of request or GC cycle), which is too late for locks or transactions.
  • register_shutdown_function only works at script end, not at block scope.

Context managers solve this by binding the cleanup to a lexical block. The cleanup runs exactly when the block exits — normally, via return, or via exception.

Python has had with since 2.5. C# has using. Java has try-with-resources. PHP v1 of this RFC (2021) proposed a two-method interface (__enter/__exit), but it never reached a vote. The v2 redesign uses generators, which are already a first-class language feature, and makes using an expression that returns a value.

The generator-based design

A context manager is simply a generator function (or a class implementing ContextManager with a getContextManager(): Generator method). The structure is fixed:

function manager(): Generator {
    // 1. Setup code runs immediately
    $resource = acquire();

    // 2. yield passes control to the block
    //    The yielded value becomes the block variable
    yield $resource;

    // 3. Cleanup runs when the block exits
    //    This runs in a finally-like fashion — always
    release($resource);

    // 4. Optional return value becomes the using-expression result
    return $result;
}

Key rules:

  • Exactly one yield. A second yield throws Error.
  • The block runs in the same scope as the caller — no closure, no use needed. A return inside the block returns from the surrounding function.
  • using is an expression (hence the trailing semicolon in examples). It evaluates to the generator's return value.
  • Multiple managers nest left-to-right: using (a() => $x, b() => $y) { ... }.

Practical examples

Timing a block

function timer(): Generator {
    $start = hrtime(true);
    yield;
    return hrtime(true) - $start;
}

$nanoseconds = using (timer()) {
    somethingSlow();
};

echo "Took " . ($nanoseconds / 1_000_000) . " ms";

The generator returns the elapsed time, which the using expression captures. No global variables, no closure boilerplate.

Database transactions

This is the killer use case. Today we write:

$db->beginTransaction();
try {
    $db->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
    $db->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
    $db->commit();
} catch (Throwable $e) {
    $db->rollBack();
    throw $e;
}

With context managers:

function transaction(PDO $db): Generator {
    $db->beginTransaction();
    try {
        yield $db;
    } catch (Throwable $e) {
        $db->rollBack();
        throw $e;
    }
    $db->commit();
}

using (transaction($db) => $conn) {
    $conn->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
    $conn->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
}

The transaction commits on normal exit, rolls back on exception. The yield $db makes the connection available inside the block. The try/catch inside the generator handles the rollback — but note: if your block throws, the exception propagates after the rollback runs.

File handles and resources

Resources (streams, sockets, curl handles) are automatically wrapped when used directly:

using (fopen('data.csv', 'r') => $fp) {
    while (($row = fgetcsv($fp)) !== false) {
        process($row);
    }
}
// fclose($fp) runs automatically

The RFC specifies that any resource passed to using gets an implicit wrapper that closes it. This works for any resource type.

Lock acquisition

function lock(Redis $redis, string $key, int $ttl = 10): Generator {
    $acquired = $redis->set($key, '1', 'NX', 'EX', $ttl);
    if (! $acquired) {
        throw new RuntimeException("Could not acquire lock: $key");
    }
    try {
        yield true;
    } finally {
        $redis->del($key);
    }
}

using (lock($redis, 'cron:billing') => $ok) {
    runBillingJob();
}

The lock releases when the block exits, even if runBillingJob() throws or returns early.

Class-based managers

For reusable logic, implement the ContextManager interface:

interface ContextManager {
    public function getContextManager(): Generator;
}

final class Stopwatch implements ContextManager {
    private int $start;

    public function getContextManager(): Generator {
        $this->start = hrtime(true);
        yield $this;
        return hrtime(true) - $this->start;
    }

    public function elapsedMs(): float {
        return (hrtime(true) - $this->start) / 1_000_000;
    }
}

$ms = using (new Stopwatch() => $sw) {
    somethingSlow();
};
echo $sw->elapsedMs(); // also available via the variable

Multiple managers and error handling

Multiple using clauses nest naturally:

using (transaction($db) => $conn, lock($redis, 'report:monthly') => $locked) {
    $conn->exec("INSERT INTO reports ...");
}

The lock acquires after the transaction starts (left-to-right). On exit, the lock releases first, then the transaction commits/rolls back.

To catch exceptions from the manager itself (e.g., lock acquisition failure), use try using:

try using (lock($redis, 'critical') => $ok) {
    doCriticalWork();
} catch (RuntimeException $e) {
    // lock() threw because it couldn't acquire
    log->warning('Skipped critical work', ['reason' => $e->getMessage()]);
}

Without try using, the exception propagates normally.

What this replaces

Pattern Today With Context Managers
File/stream handling try/finally + fclose using (fopen(...) => $fp)
DB transactions beginTransaction + try/catch/commit/rollBack using (transaction($db) => $conn)
Locks / semaphores try/finally + release using (lock(...) => $ok)
Timing / profiling $start = hrtime(); ...; $elapsed = hrtime() - $start $elapsed = using (timer()) { ... }
Temporary state changes try/finally + restore using (tempConfig(...)) { ... }

Gotchas and open questions

The RFC is still a draft (v2.0 as of October 2026) and several details are unsettled:

  • Return value with multiple managers: Currently the using expression returns the last manager's return value. This may change.
  • ContextManager interface shape: Whether it stays as getContextManager(): Generator or gets refined.
  • Interaction with fibers: Generators and fibers both suspend execution. The RFC authors are clarifying the semantics when a context manager is used inside a fiber.
  • No vote scheduled yet. It needs a ⅔ majority on internals to pass.

When to use it (once it lands)

  • Adopt immediately for transactions, locks, and resource handles. The cleanup guarantee is stronger and the code is shorter.
  • Use for timing when you need the result inline without a closure.
  • Wrap legacy cleanup patterns in generator functions to migrate gradually.
  • Avoid for trivial one-liners where try/finally is already clear.

Migration path for existing code

If you maintain a library with setup/cleanup helpers, you can make them context-manager-aware without breaking callers:

// Old API — still works
function withLock(callable $callback): mixed {
    $lock = acquire();
    try {
        return $callback();
    } finally {
        release($lock);
    }
}

// New API — same function, dual-purpose
function lock(): Generator {
    $lock = acquire();
    try {
        yield $lock;
    } finally {
        release($lock);
    }
}

// Callers can use either style
withLock(fn() => doWork());           // old
using (lock() => $l) { doWork(); }    // new

Summary

Context Managers v2 brings a missing control-flow primitive to PHP. By building on generators, it reuses existing language machinery instead of adding new magic methods. The using expression is concise, scope-safe, and returns a value — making it practical for the patterns we write daily: transactions, locks, file handles, and timed blocks.

The RFC is targeting PHP 8.7. If you maintain code that does any kind of scoped resource management, it's worth reading the full proposal and the internals discussion to understand the edge cases before it lands.


Sources