Scope View as Markdown

Under discussion
▴ 1 ▾ 0
community vote
Authors
Frode Børli, frode@ennerd.com
Date
2026-11-13
Version
0.10
Implementation
https://github.com/fiber-interop/ext-scope (extension); php-src pull request to follow
Source
wiki.php.net/rfc/scope

Votes

Add Scope and Generator::getScope() as described in this RFC? no votes
Yes · No · Abstain
A. Should $_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST, $_SERVER and the session ($_SESSION and ext/session's state) follow the current scope as described, a new scope starting as a copy of its creator's? no votes
Yes · No · Abstain
B. Should the default locale and the default timezone follow the current scope as described? no votes
Yes · No · Abstain

Discussions on the mailing list

[RFC] Scope
· 17 messages

RFC text

Copied from wiki.php.net, last synchronized Nov 13, 2026 17:46 UTC

Introduction

This RFC adds Scope, an object that identifies a unit of work: an HTTP request, a queue job, a CLI command.

Until now a PHP request has been one run of the engine, from startup to shutdown, so PHP never needed an object for it. PHP increasingly runs as a long-lived server that handles many requests in one process, often concurrently, with fibers. Such a server, and every library running in it, needs to know which request the code that is running belongs to. PHP has no answer to that today. Each runtime invents its own (phasync has phasync::getContext(); others key state by Fiber::getCurrent(), which is wrong as soon as a request starts a second fiber), and a library written for one runtime cannot use another's.

Scope is that answer, and nothing more. It holds no values, runs nothing, and owns no fibers. Code asks for Scope::getCurrent() and gets the same object everywhere in the same request, including in the fibers and generators it starts, whichever library starts them. A container or library keeps per-request state in a WeakMap keyed by it; the state is freed when the request's scope is.

Code that never creates a scope runs in the root scope and behaves exactly as today.

Two secondary votes use the scope to give request state an owner: the request superglobals and the session (vote A), and the default locale and timezone (vote B). They are the state that concurrent requests in one process currently overwrite for each other.

Proposal

The class

final class Scope
{
    /** A new scope. It becomes current only inside run() or a closure from bind(). */
    public function __construct() {}
 
    /**
     * Calls $callback in this scope and returns its result. The frame created for $callback,
     * and every frame created from it, belong to this scope. When $callback returns or throws,
     * execution continues in the caller's frame, which still belongs to its own scope.
     */
    public function run(callable $callback, mixed ...$args): mixed {}
 
    /**
     * Returns a copy of $closure that always runs in this scope, whoever calls it: each call
     * creates its frame in this scope, as run() does. The copy keeps $closure's signature,
     * $this and class scope; $closure itself is unchanged. Binding a bound closure replaces
     * the binding.
     */
    public function bind(Closure $closure): Closure {}
 
    /** The scope of the frame that is executing. Never null: outside any scope, the root scope. */
    public static function getCurrent(): Scope {}
 
    /** The scope of {main}: one object per PHP request (per process under the CLI). */
    public static function getRootScope(): Scope {}
}
 
final class Generator
{
    /** The scope of this generator's frame: the scope it was created in. */
    public function getScope(): Scope {}
}

The rule: a scope belongs to a stack frame

Every stack frame has a scope. It is assigned when the frame is created: the scope of the frame that created it, unless the frame is created by $scope->run() or by calling a closure from $scope->bind(), which give it $scope. It never changes while the frame exists. The current scope is the scope of the frame that is executing.

That is the whole model. Everything below follows from it, fibers and generators included.

{main}'s frame has the root scope, so a program that never creates a scope runs entirely in the root scope.

Functions and closures

Calling a function or closure creates a frame, which gets the caller's scope. A closure does not capture a scope when it is defined: a closure is code, not a frame. The same closure runs in one scope when one request calls it, and in another when another request does.

$handler = function () {
    return Scope::getCurrent();
};
 
$a = new Scope();
$b = new Scope();
var_dump($a->run($handler) === $a);   // bool(true)
var_dump($b->run($handler) === $b);   // bool(true)
var_dump($handler() === Scope::getRootScope());   // bool(true)

This is what applications need. They create route handlers, middleware, listeners and container factories once, at startup, in the root scope, and call them during requests. If closures captured their creation scope, every handler would run in the root scope.

Internal functions that call back (array_map(), usort(), preg_replace_callback()) create frames like any caller, so callbacks run in the current scope with nothing to switch. A destructor's frame is created where the object is released, so it runs in the scope that is current at that point. An object that needs a particular scope for its cleanup captures it at construction and calls $scope->run() in its destructor.

run()

$scope->run($callback) creates the frame for $callback in $scope instead of the caller's. Frames that frame creates inherit $scope. When $callback returns or throws, execution is back in the caller's frame, whose scope never changed. Nothing needs restoring; calls nest naturally:

$a->run(function () use ($b) {
    // in $a
    $b->run(function () {
        // in $b
    });
    // in $a: this frame's scope never changed
});

run() takes any callable, partial function applications included. The placeholder decides whether the call happens inside the scope:

$scope->run(handle($request, ...));   // handle() runs in $scope
$scope->run(handle($request));        // handle() runs in the caller's scope; run() is given its result

A scope keeps no link to the scope it was run from (see Rejected Features).

Generators

Calling a generator function creates the generator's frame, as calling any function creates a frame. A Generator object is that frame, suspended between steps. So it has the scope of the code that called the generator function, and keeps it across every yield, whoever resumes it:

$scope = new Scope();
$gen = $scope->run(function () {
    return (function () {
        while (true) {
            yield Scope::getCurrent();
        }
    })();
});
 
var_dump($gen->current() === $scope);   // bool(true), although the root scope resumed it
$other = new Scope();
$other->run(fn() => $gen->next());
var_dump($gen->current() === $scope);   // bool(true)

This is not a special case: it is the frame rule applied to a frame that outlives its call. It matters for streamed responses: an application returns a response-body generator from its request, and the server consumes it later from its own loop. The generator still sees its request's services, superglobals and connection:

// In the application, inside the request:
return new Response(body: (function () use ($db) {
    foreach ($db->pdo()->query('SELECT ...') as $row) {   // this request's connection
        yield json_encode($row);
    }
})());

With yield from, the inner generator runs in its own frame's scope, the scope it was created in.

bind()

A closure has no scope, so a closure registered in one request and called from another runs in the caller's. When that is wrong, the code that registers it binds it: $scope->bind($closure) returns a closure whose every call creates its frame in $scope.

// Registered while handling an order request:
$bus->on('order.paid', Scope::getCurrent()->bind(function (Event $e) {
    // runs in the order request's scope, whichever scope dispatches the event
}));

bind() is to scopes what Closure::bind() is to $this. It differs from a userland wrapper such as fn(...$a) => $scope->run($closure, ...$a) in that the result keeps $closure's by-reference parameters, defaults, return type, $this and class scope, and is the same kind of closure. Node's AsyncLocalStorage.bind() and TC39's AsyncContext.Snapshot.wrap() serve the same purpose.

Fibers

A fiber is not a special case either. Constructing a fiber creates no frame; $fiber->start() creates its first frame, and that frame gets the scope of the code that calls start(), like any call. From then on the fiber's frames keep their scopes while it is suspended, and resuming it from another scope changes nothing:

$scope = new Scope();
$fiber = new Fiber(function () {
    var_dump(Scope::getCurrent());   // $scope
    Fiber::suspend();
    var_dump(Scope::getCurrent());   // still $scope
});
 
$scope->run(fn() => $fiber->start());           // started in $scope: its first frame is $scope's
(new Scope())->run(fn() => $fiber->resume());   // resumed from another scope: still $scope

Most code starts a fiber where it constructs it, so a library's fibers (an HTTP client's parallel requests, a driver's pool) belong to the request that called the library, without the library doing anything. When starting is deferred to a scheduler, the scheduler runs the start as a queued callback, and an event loop already runs each callback in the scope it was queued from (see Using a scope: event loops), so the fiber again starts in the request's scope. Code that hands a fiber to something that starts it from another scope, and wants the fiber in its own, binds the closure:

$fiber = new Fiber(Scope::getCurrent()->bind($work));   // starts in this scope, whoever starts it

Fibers reused for many callbacks, as in Revolt's callback fiber, need nothing: each callback is a new frame in the scope its loop runs it in.

The root scope

Scope::getRootScope() is the scope of {main}, and so of all code outside any run(). It lives as long as the PHP request:

  • under the CLI, that is the whole process;
  • under php-fpm and other SAPIs that serve several requests per process, each request has its own root scope, so nothing changes for code that never creates a scope.

getCurrent() always returns an object, so a scope can always be a WeakMap key and callers never handle null. Scope::getCurrent() !== Scope::getRootScope() tells code whether it runs inside an explicit scope. A long-running server's own loop runs in the root scope and creates a scope for each request it handles.

Lifetime

A scope has no start or end event. It is an ordinary object: it stays alive while something references it (a frame, a fiber, a generator, a queued callback, a request object) and is freed when nothing does. A server releases its references when the request is done; once the last fiber, generator and callback of that request is gone, the scope goes, and so do WeakMap entries keyed by it.

A scope does not wait for fibers, cancel work or finish when run() returns. It may be entered any number of times, from any fiber.

A Scope is not serializable. It identifies work inside one process; to pass a trace or request id to another process, send the id.

What follows the scope, and what does not

The primary vote moves no state at all: Scope is only an identity. Global variables and static properties never follow the scope, including under the secondary votes. Applications use them for caches, registries and singletons, and building those once and keeping them across requests is the reason to run as a long-lived server. If they followed the scope, every request would start cold.

State Belongs to Follows the scope
class statics, function statics, $GLOBALS the application, shared on purpose no
$_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST, $_SERVER, $_SESSION and ext/session's state the request yes, if vote A passes; a new scope starts as a copy of its creator's
default locale, default timezone the request yes, if vote B passes; a new scope starts as a copy of its creator's
output buffers, header(), error and exception handlers, ini_set() values the request later, one RFC each
json_last_error(), preg_last_error(), error_get_last() the call just made no: see below
$_ENV, setlocale(), chdir(), umask() the process no
persistent connections (PDO::ATTR_PERSISTENT, pg_pconnect(), mysqli p:, pfsockopen()) the process later, on its own: see below

Every kind of state that follows the scope starts, in a new scope, as a copy of the creator's. That is one rule for the two votes here and for whatever later RFCs add, and it is what lets them be added without disturbing code written before them: a scope that never mentions the new state sees its creator's values, as it did while the state was process-wide, and only code that sets the state inside a scope sees a change, which is the containment a scope is for. Versions 0.9 to 0.9.5 of this text had a new scope start empty instead; the discussion showed that empty-start turns every later addition into a behaviour change for code that merely reads the state, and that “empty” would need its own definition for each kind of state. Response output is the one kind of state the copy rule does not fit, and is discussed under Future Scope. The list there is the full picture this RFC takes the first step of.

Last-error functions need no isolation: fibers switch only when they suspend, so nothing runs between json_decode() and the json_last_error() that follows it.

Persistent connections are cached process-wide by their parameters, so two scopes can get the same database session at once, and a transaction in one would affect the other. A later RFC should lend a persistent connection to one scope at a time; until then, concurrent scopes should use non-persistent connections or a pool. This affects PDO, pgsql, mysqli and streams, and is not part of this RFC.

Using a scope: request-lifetime services

Scope is not a service locator, and the RFC does not propose that application code look anything up through it. It is what a dependency injection container needs in order to offer the lifetime other platforms call scoped: one instance per request, shared by everything in that request, between a singleton (one per process) and a transient (one per resolution). Classes keep receiving their dependencies through their constructors; only the container, which code calls from the request's frames, sees the scope.

A complete PSR-11 container with the three lifetimes:

final class Container implements Psr\Container\ContainerInterface
{
    private array $shared = [];
    private WeakMap $scoped;   // Scope => that scope's services
 
    /** @param array<string, array{Closure(self): mixed, 'singleton'|'scoped'|'transient'}> $services */
    public function __construct(private array $services)
    {
        $this->scoped = new WeakMap();
    }
 
    public function get(string $id): mixed
    {
        [$make, $lifetime] = $this->services[$id] ?? throw new NotFound($id);
 
        if ('scoped' === $lifetime) {
            $mine = $this->scoped[Scope::getCurrent()] ??= new ArrayObject();
 
            return $mine[$id] ??= $make($this);
        }
 
        return 'singleton' === $lifetime ? $this->shared[$id] ??= $make($this) : $make($this);
    }
 
    public function has(string $id): bool
    {
        return isset($this->services[$id]);
    }
}

The container is built once, in the root scope, and is not bound to it: get() creates its frame in the scope of whoever calls it, so it sees the request's scope. The request's scoped services are freed with that scope, without the container ever hearing that the request ended.

A singleton must not keep a scoped service it received in its constructor, the same rule as .NET's ValidateScopes. When a long-lived service needs a per-request resource, it depends on a small singleton that resolves the resource per scope, as Spring's scoped proxies do:

final class TenantConnection
{
    private WeakMap $byScope;
 
    public function __construct(private Closure $open) { $this->byScope = new WeakMap(); }
 
    public function pdo(): PDO
    {
        return $this->byScope[Scope::getCurrent()] ??= ($this->open)();
    }
}

Libraries store per-scope data in their own WeakMaps. They need no shared registry and no naming convention for keys, and only the code that holds a map can reach what is in it.

Using a scope: event loops

Fibers carry their scope; callbacks, which have none, do not. An event loop that queues callbacks keeps the registering scope with each:

// When the callback is registered:
$this->queue[] = [Scope::getCurrent(), $callback];
 
// When it is due:
[$scope, $callback] = array_shift($this->queue);
$scope->run($callback);

The queue's reference keeps the scope alive until the callback has run.

Secondary vote A: the request superglobals and the session follow the scope

Six superglobals hold request data: $_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST and $_SERVER; $_SESSION and ext/session hold the session. Today they are one set per process, so two overlapping requests overwrite each other's input and session unless the server avoids them altogether. $_ENV is process state and is not included.

If vote A passes, each scope has its own set:

  • The root scope's are the ones the SAPI populates, so nothing changes for code that never creates a scope.
  • A new scope starts as a copy of the scope that is current when it is constructed: the six arrays hold the same values, and the session is in the same state (the same id, status and $_SESSION). The copy is PHP's copy of an array: nothing is duplicated until one side writes, and an object held in an array is the same instance in both scopes, as in any copied array. From then on the two are independent: an assignment inside the new scope changes only its own array, and the creator's values stay as they were when the copy was made.
  • The copy is what makes a scope safe to create anywhere. Code that runs inside a scope it knows nothing about, such as a legacy function that reads $_GET and $_SESSION forty calls below the run(), sees the values its caller saw, and what it changes does not reach the caller. The same rule holds for every kind of state a later RFC adds to the scope: it starts as a copy, so code that never sets it is not affected by the addition, and code that does set it keeps the change to itself.
  • A server that starts a request wants a fresh set, and gets one by constructing the request's scope from its own loop, which runs in the root scope: under the CLI the root's arrays are the CLI's and no session is active, so the copy is as good as empty, and the server fills the six as it does today (see below). Code that wants a scope emptier than its creator's assigns or unsets what it does not want to pass on. There is no constructor option for starting empty (see Rejected Features).
  • Reads and writes inside a scope use that scope's arrays. All frames of the scope share them, in every fiber and generator.
  • $_REQUEST is a per-scope array like the others, not a live merge, as today.
  • $_SERVER mixes request facts (REQUEST_URI, REQUEST_METHOD, HTTP_*, REMOTE_ADDR) with the environment (PATH, DOCUMENT_ROOT). A new scope's is a copy of its creator's like the others; constructed from the root scope, that is the environment, and the server writes the request's own entries over it. Left shared, it would hold whichever request wrote it last.
  • The session is the scope's: session_start() inside a scope starts that scope's session, and its state ($_SESSION, id, status, save handler and data) is the scope's alone. The session.* ini settings, and session_name(), session_set_cookie_params() and the other functions that set them, stay request-wide like any ini_set() value. The session is written and closed by session_write_close() inside the scope, or at the latest when the scope is freed with the session still active. A scope constructed while a session is active holds a copy of it: the same id and status and a copy of $_SESSION. It does not open the session again, so a locking save handler's lock is not taken twice; the lock is held and released by the scope that opened the session. A session_write_close() in the copy writes its $_SESSION under that id, and the scope that opened the session writes its own when it closes it, so the later write wins, as when code keeps a copy of $_SESSION in a variable and restores it. That is the same containment as for the six arrays: what the copy changes does not reach its creator. The headers session_start() sends belong to the scope's response; until headers follow the scope (see Future Scope) the server routes them, as it routes the rest of each response.
  • A session whose save handler locks can be open in one scope of a process at a time. A second scope opening the same session id, as a browser's parallel requests do, would otherwise wait for a lock only the first scope can release, while the process waits and the first scope cannot run. session_start() therefore throws a RuntimeException in that case, without the id in the message. A scope that holds a copy of an active session has not opened it, and is not a second opening. Locks held by other processes or threads are waited for as today; handlers that do not lock behave as under php-fpm.

The server fills them, not the application. Whatever creates the request's scope (Swerve, FrankenPHP, RoadRunner) populates it, once, in the same place where it fills the superglobals today. In this example $request is the server's own parsed HTTP request and $app the application's entry point:

// For each request the server accepts, from its loop in the root scope:
(new Scope())->run(function () use ($request, $app) {   // a copy of the root's: the CLI's arrays, no session
    $_GET    = $request->query;
    $_POST   = $request->parsedBody;
    $_COOKIE = $request->cookies;
    $_FILES  = $request->uploads;
    $_SERVER = $request->serverParams + $_SERVER;   // the request's entries over the environment the copy brought
    $app->handle();   // the application, and every fiber it starts, sees this request's values
});

A scope created to guard the current state rather than to start a request, as a test or a plugin host does around code it does not trust with its superglobals, needs no setup at all: the code inside sees what the creator sees, and leaves it as it found it.

Two scopes hold different values at the same time, and the root's are untouched:

$a = new Scope(); $b = new Scope();
$a->run(fn() => $_GET = ['page' => '1']);
$b->run(fn() => $_GET = ['page' => '2']);
$a->run(fn() => var_dump($_GET['page']));   // string(1) "1"
var_dump($_GET);                             // the SAPI's array, unchanged

$GLOBALS['_GET'] and global $_GET refer to the current scope's array. A reference taken in one scope, such as $g = &$_GET, keeps referring to that scope's array after a switch.

Implementation. Constructing a scope copies the current scope's six zvals and ext/session's state into it, a reference count increment per array, as for any array copy. The engine swaps the six entries of the global symbol table (and PG(http_globals)) and ext/session's state when the current scope changes, saving the outgoing scope's and loading the incoming one's. No array is duplicated until one side writes, and reads and writes cost what they cost today. Whether a save handler locks is declared by a new field of ps_module: the files handler sets it, PECL redis and memcached can set it from their locking settings, a user handler extending SessionHandler locks when the handler it wraps does, and other user handlers are taken not to lock.

The extension implements this vote, on by default and switchable with scope.superglobals=0 (and scope.session=0 for the session) so it can be evaluated on its own; its current release starts a new scope empty, and the copy follows in the next. The userland polyfill does the same when an event loop reports scope changes; https://fiber-interop.github.io/conformance.html (column “Scope state”) shows which event loops can report every change and which cannot, which is the case for doing it in the engine.

Secondary vote B: the default locale and timezone follow the scope

Locale::getDefault()/Locale::setDefault() (ext/intl) and date_default_timezone_get()/date_default_timezone_set() operate on one process-wide setting today, so two concurrent requests cannot use different defaults. If vote B passes, these defaults follow the scope: the root keeps the SAPI's, a new scope starts with its creator's current defaults, and setting either changes only the current scope's. ini_set('date.timezone') stays request-wide: a scope that has set its own timezone ignores it, one that has not, and a copy of one that has not, follows it, as does intl.default_locale.

The extension implements this vote too (scope.locale_timezone=0 turns it off); as under vote A, its current release starts a new scope from the ini values, and the copy follows in the next. The timezone is one pointer swap per scope change; the locale, whose globals ext/intl does not expose, is applied through intl.default_locale only when it differs. In core both are plain swaps. This is a separate vote because ext/intl and ext/date have their own maintainers, and ICU's process-wide default needs their review.

Why in core

The identity can almost be built in userspace, and phasync has done so for two years: a context attached to each fiber, inherited by the fibers it starts. It does not quite work:

  1. Generators cross fibers. A generator passed from one request to another, concurrent one can produce one value in one fiber and the next in another. From userspace, the only way to know which request a generator belongs to is to pass an identifying token into it.
  2. Every runtime has its own. phasync, Amp and ReactPHP each tie code to a request their own way, so a library has to pick one or carry adapters for all. The fragmentation exists because core has no common identity.
  3. Cost. In the engine the current scope is a pointer saved and restored at fiber and generator switches. In userspace every lookup goes through the runtime, and generators cannot be followed at all.
  4. Superglobals. Only the engine can make $_GET and the session follow the request (vote A). Removing the process-wide nature of superglobals answers one of the oldest criticisms of PHP, without asking any code to change.
  5. No store. The engine adds only the identity. A Scope that stored values would invite a global service locator with string keys; a WeakMap per library keeps state private to the code that owns it.

What remains is the class of bug every platform meets when one process serves thousands of concurrent requests: shared resources need limits and pools. Scope does not cause that; concurrency does.

Prior art

Other platforms give each unit of work an identity that follows it across asynchronous boundaries, and let containers and libraries, not application code, use it:

  • .NET: ExecutionContext flows across await; AsyncLocal<T> holds “ambient data that is local to a given asynchronous control flow”. Microsoft.Extensions.DependencyInjection has ServiceLifetime.Scoped, ASP.NET Core creates one IServiceScope per request, and ValidateScopes rejects a scoped service injected into a singleton.
  • Java: Spring's @RequestScope and Jakarta CDI's @RequestScoped give singletons a proxy that finds the current request's instance through a ThreadLocal. Scoped values (JEP 506, JDK 25) are bound for the duration of a run() call and inherited by the threads of a StructuredTaskScope, including virtual threads.
  • JavaScript: Node's AsyncLocalStorage, with run() and bind(); NestJS's request-scoped providers and awilix's createScope() use it. TC39's AsyncContext (Stage 2) puts it in the language. Generators keep the context they were created in, as in this RFC; other functions run in their caller's.
  • Python: contextvars (PEP 567), with Context.run(); asyncio runs each task in a copy of the context current when it was created.
  • Kotlin and Swift: a coroutine inherits its launcher's CoroutineContext; Swift task-locals (SE-0311) are inherited by child tasks, not detached ones.
  • Go: context.Context is passed explicitly as the first parameter of every function. That works because Go's ecosystem adopted it from the start. PHP's has not, and fibers are created inside code that has no parameter to pass a context through.

In PHP, Laravel's scoped bindings and Symfony's service resetting do the same job for workers that serve one request at a time, without a shared identity.

Earlier PHP proposals. The Fibers RFC left scheduling to libraries and did not distinguish application state from request state. The Concurrency Support RFC gives each coroutine its own engine state; this RFC gives it to the request, which may span several fibers that today share output buffers, locale and timezone. The two can work together: a scheduler can assign its coroutines to scopes. The Async Scope proposal also uses the name Scope, for a group of coroutines whose lifetime it controls; this Scope owns no execution, and a scheduler could use both. Context was considered, but implies a collection of values and is already used by stream contexts.

Backward Incompatible Changes

A class named Scope can no longer be declared in the global namespace; namespaced classes are unaffected. Of the first 100 results of a GitHub code search for PHP files declaring class Scope, 88 are namespaced and 2 global (a toy interpreter, and a project last changed in 2018; a second sample on 2026-10-14 found 3 of 100). None of the top 1000 Composer packages (Packagist's list of 2026-10-26, 998 parsed with nikic/php-parser) declares or aliases a global Scope; the 34 declarations in 14 packages, among them Illuminate\Database\Eloquent\Scope, are namespaced.

Proposed PHP Version(s)

Next PHP 8.x (PHP 8.7).

RFC Impact

To the ecosystem. IDEs, language servers and static analysers need stubs for Scope and Generator::getScope(); no syntax changes. Libraries can adopt Scope today through the polyfill fiber-interop/scope, which declares the class on PHP 8.2 and later. Code that keys state by Fiber::getCurrent() can key it by Scope::getCurrent().

To SAPIs. None for the primary vote. Under vote A, SAPIs keep populating the superglobals as now; they become the root scope's.

To existing extensions. None for the primary vote. Vote B touches ext/intl and ext/date.

To opcache. None. New constants, php.ini defaults. None.

Open Issues

Session locking within a process. This RFC has session_start() throw when a locking handler's session id is open in another scope of the process. The alternative is for the two scopes to share one session, one $_SESSION and one lock: no error, but no isolation either.

Unaffected PHP Functionality

Code that never creates a Scope runs in the root scope and behaves exactly as before. Fiber behaves as before, Generator apart from getScope(), and state not covered by the secondary votes stays process-wide.

Future Scope

Each kind of request state can follow the scope in its own RFC, leaving code outside explicit scopes unchanged:

  • Headers and the response body are not values to copy. A header set inside a scope, or a byte echoed there, must still reach the one response the request has; a new scope that started with a copy of its creator's header list and output stack, and discarded them when it went, would lose them. They are a sink that the creator of the scope supplies, by default its own, not state the copy rule can carry. That is why they need the integration points below rather than this RFC's copy rule, and why they are not a vote here.
  • Output buffering. ob_start() serves request output, which belongs to the request and all its fibers, and capture of a piece of code's output (a template), which belongs to that block. A future RFC could make request output follow the scope and add a separate structured capture, such as ob_context_run(callable): string, so a suspended capture cannot pop another fiber's buffer.
  • The response: header(), headers_list(), headers_sent(), http_response_code() and the sink that receives the body, exposed so that a server can supply them per scope.
  • Error and exception handlers, ini_set() values and shutdown functions.
  • An internal API for per-scope extension state: module globals with a scope's lifetime, allocated when a scope first touches them, the root holding today's request state.
  • Persistent connections lent to one scope at a time.
  • Operations on a scope as a whole, such as cancellation. That needs its own design: when a fiber observes it, how finally runs, and a way to find a scope's fibers, which this RFC does not keep.

State owned by the operating system (setlocale(), chdir(), umask(), the environment, syslog's identity) cannot cheaply follow a scope.

Voting Choices

Primary vote, 2/3 majority:

Vote: Add Scope and Generator::getScope() as described in this RFC? — Yes: 0 · No: 0 · Abstain: 0 (closed)

Secondary votes, 50%+1 each, counted only if the primary vote passes; B does not depend on A:

Vote: A. Should $_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST, $_SERVER and the session ($_SESSION and ext/session&#039;s state) follow the current scope as described, a new scope starting as a copy of its creator&#039;s? — Yes: 0 · No: 0 · Abstain: 0 (closed)

Vote: B. Should the default locale and the default timezone follow the current scope as described? — Yes: 0 · No: 0 · Abstain: 0 (closed)

Generators are in the primary vote because they follow from the frame rule. Leaving them out would make generators run in whatever scope resumes them, code would come to depend on that, and fixing it later would be a backward incompatible change.

Patches and Tests

fiber-interop/ext-scope 0.6.0 implements this RFC, including the frame rule for fibers and both secondary votes, with one difference: a new scope starts empty there, and the copy rule of this version follows in its next release. It is released for PHP 8.2 to 8.5 (https://github.com/fiber-interop/ext-scope, pie install fiber-interop/ext-scope), with phpt tests for each rule, on NTS and ZTS, with and without opcache, under the tracing and function JIT on 8.5, and with the parallel extension running scopes in several threads. The polyfill fiber-interop/scope 0.6.0 has the same class and tests, and is released together with the extension. A pull request against php-src master will accompany the RFC before the vote.

Implementation

The rule is stated per frame, but the engine does not store a scope in every frame. All frames between two switch points share a scope, so it keeps one current-scope pointer in the executor globals, and saves and restores it only where the executing frame can change to one with a different scope:

  • run() and a call to a bound closure save the pointer, set it, and restore it when the call returns or throws (and before a fatal-error bailout continues);
  • a fiber stores the current scope while it is suspended, and a generator its frame's scope; switching into one loads its scope, switching out saves it. start() is an ordinary call: the fiber's first frame gets the caller's scope.

Ordinary calls pay nothing. The saved pointers of a fiber suspended inside nested run() calls are visible to the cycle collector.

The tests cover, among other things: a fiber that suspends inside $scope->run() and is resumed from another scope; a fiber started in one scope that suspends inside another's run() and is then dropped, with both scopes collected afterwards, also through cycles; a fatal error inside nested run() calls with fibers suspended in them; generators consumed from other scopes across many yields and through yield from; a generator inside a fiber that suspends while the generator is inside run(); and, for vote A, unset($_GET) and global $_GET in scopes.

An extension cannot add fields to native fiber and generator objects, so the prototype keeps each one's scope in a WeakMap, follows fibers through the fiber switch observer, and compiles scope switches into generator bodies. PHP 8.5.12, x86-64, opcache on, JIT off, median of 5 runs:

Without With the extension
Function call ~23 ns ~23 ns
Generator step ~37 ns ~57 ns
Fiber resume and suspend ~110 ns ~141 ns
Generator step in another scope (switch in and back out) n/a ~240 ns

The last row switches the six superglobals, the session, the locale and the timezone in and out on every step; it is paid only when the scope changes. In core, fibers and generators hold the scope pointer directly; the php-src patch will include its own measurements.

Threads

Under ZTS the current scope and the root scope live in the executor globals, so each thread has its own. A Scope never crosses threads, as no PHP object does, and no lock enters the design. Scopes multiplex one thread's request state between operations, as threads multiplex a process between executors; a server can use both.

Rejected Features

  • A link to the parent scope (getParentScope()). Code that wants a hierarchy can keep one in a WeakMap<Scope, Scope>. In core it would keep every ancestor alive: an application that creates each scope from the previous one, millions of times, would hold the whole chain.
  • Fibers capturing the scope at construction (versions up to 0.9.5). It made a fiber the one exception to the frame rule, for the case where a fiber is constructed in one scope and started from another. Schedulers that defer start() run it as a queued callback, which already restores the queuing scope, and new Fiber($scope->bind($fn)) covers the rest explicitly.
  • Closures capturing their creation scope. Handlers are created at startup and called during requests; they would all run in the root scope. bind() captures explicitly where that is wanted.
  • run(Closure $callback) without arguments. run(fn() => f(1, 2)) is the clearest form and works with either signature. callable with ...$args matches Fiber::start(), call_user_func() and register_shutdown_function(), and also accepts partial applications with open parameters, run(f(1, ?), 2). Dropping the $fn, ...$args pattern is worth considering for PHP as a whole, in its own RFC, not in the first API to break ranks.
  • A scope that must be passed explicitly, without inheritance. Every library that creates fibers would have to pass it on, which is the interoperability problem this RFC solves.
  • null outside any scope. Every consumer would handle two cases, and adding a root later would change what existing code observes.
  • One thread per request under ZTS. A request's fibers must share its state, most deployments are NTS, and scopes work inside threads anyway.
  • A new scope that starts empty (versions 0.9 to 0.9.5), and a constructor option to choose between empty and copy. Empty needs a definition of empty for each kind of state, now and in every later RFC, and makes each addition a change for code that only reads the state. A copy is one rule, costs a reference count, and makes later additions safe for existing code. Code that wants less than its creator has clears it, and a server gets a fresh set by constructing from the root scope, so no use for the option is known; it can be added later without breaking anything, while defining it now means defining “empty” per kind of state after all.
  • Sharing the creator's state instead of copying it. A change inside the scope would be visible outside it, the leak a scope exists to prevent.

References

Changelog

  • 0.9.1 (2026-10-26): first version on the wiki; announced on internals.
  • 0.9.2 (2026-10-27): Introduction rewritten; no change to the proposal.
  • 0.9.3 (2026-10-27): vote A: session_start() throws instead of blocking when a locking handler's session id is open in another scope of the process.
  • 0.9.4 (2026-10-28): implementation: in the engine, per-scope state is reached through the current scope, so a switch costs a few pointer stores whatever the scopes hold.
  • 0.9.5 (2026-11-06): from the discussion: why a scope has no parent link, run() with partial function application, who uses Scope directly, statics and $GLOBALS. No change to the proposal.
  • 0.10 (2026-11-13): rewritten around one rule, that a scope belongs to a stack frame and is assigned when the frame is created, with no special cases. Changed: a fiber no longer captures the scope at construction; its first frame gets the scope of the code that calls start(), and new Fiber($scope->bind($fn)) gives a fiber a fixed scope. Fiber::getScope() is removed. Added: a container example with the three lifetimes in place of the service-locator example, Why in core, the root scope under the CLI and php-fpm, the server's role in vote A, and the parent link, closure capture and run(Closure) under Rejected Features. From the discussion (Larry Garfield, Côme Chilliet): a new scope starts as a copy of its creator's state instead of empty, under vote A (the six arrays and the session) and vote B (locale and timezone), with no option to start empty; the session copy's semantics; why response output is a sink and not state to copy (Future Scope); the copy rule as what makes later additions safe (What follows the scope); empty-start and shared state under Rejected Features.