[PHP-DEV] [RFC] Scope

Hi internals,

I’d like to start the discussion on a new RFC:

https://wiki.php.net/rfc/scope

PHP has no object that represents a request. The request is the period

between startup and shutdown, and its state lives in process-wide

globals. That works while a process handles one request at a time, but

not when one process serves many requests, and least of all when they

overlap.

The RFC adds Scope: an object that identifies a unit of work, such as

an HTTP request, a queue job or a CLI command. Code can create a scope,

run code in it, and ask which scope it is running in:

(new Scope())->run($handler, $request);

// anywhere in that request:

$db = $this->connections[Scope::getCurrent()] ??= new PDO($dsn);

Fibers and generators join the scope they are created in, so work a

request spreads over several fibers still belongs to that request,

whichever library or scheduler created them. Code that never creates a

scope runs in the root scope and behaves exactly as today.

The primary vote adds only the identity. Two secondary votes move

engine state into the scope:

A. the request superglobals and the session

B. the default locale and timezone

Other state (output buffers, error handlers, ini values) is left for

later RFCs, so each can be discussed on its own.

An extension implementing the RFC, including both secondary votes, is

available for PHP 8.2 to 8.5:

https://github.com/fiber-interop/ext-scope

(pie install fiber-interop/ext-scope)

A userland polyfill is fiber-interop/scope on Packagist. A php-src

pull request will follow before the vote.

I look forward to your feedback.

Frode Børli

On Mon, Oct 26, 2026, at 11:03 AM, Frode Børli wrote:

Hi internals,

I'd like to start the discussion on a new RFC:

PHP: rfc:scope

PHP has no object that represents a request. The request is the period
between startup and shutdown, and its state lives in process-wide
globals. That works while a process handles one request at a time, but
not when one process serves many requests, and least of all when they
overlap.

The RFC adds Scope: an object that identifies a unit of work, such as
an HTTP request, a queue job or a CLI command. Code can create a scope,
run code in it, and ask which scope it is running in:

    (new Scope())->run($handler, $request);

    // anywhere in that request:
    $db = $this->connections[Scope::getCurrent()] ??= new PDO($dsn);

Fibers and generators join the scope they are created in, so work a
request spreads over several fibers still belongs to that request,
whichever library or scheduler created them. Code that never creates a
scope runs in the root scope and behaves exactly as today.

The primary vote adds only the identity. Two secondary votes move
engine state into the scope:

  A. the request superglobals and the session
  B. the default locale and timezone

Other state (output buffers, error handlers, ini values) is left for
later RFCs, so each can be discussed on its own.

An extension implementing the RFC, including both secondary votes, is
available for PHP 8.2 to 8.5:

GitHub - fiber-interop/ext-scope: Scope: a PHP extension implementing the Scope RFC. Identifies the operation code belongs to, across fibers and generators. · GitHub
(pie install fiber-interop/ext-scope)

A userland polyfill is fiber-interop/scope on Packagist. A php-src
pull request will follow before the vote.

I look forward to your feedback.

Frode Børli

Minor thoughts as I read through it:

- Given that we now have PFA, which means turning pretty much any call into a closure involves just adding ... to it, do we still want to have `run(callable, ...$args)`? `run(Closure $c)` would work just as well, and be callable like

$scope->run(doAThing(1, 2, 4, ...));

I'm not certain here, but it's worth considering if we can go a step further now.

- The docblock on Scope::bind() is horribly confusing and clumsy. It took me 5 reads to understand what it was saying. I *think* the idea is to "change" the scope object inside a closure, just like Closure::bind() changes the $this object inside a closure. Yes? (And returns new rather than modifying in place, but...)

- "A scope keeps no link to the scope it was run from." So that fully precludes getParentScope() and such, yes? What is the reason for avoiding that? (Not that I disagree, but I want to understand why.)

- "The root scope is a single object that lives as long as the PHP request:" - I think you mean "PHP process" here, as the process is not always isomorphic with an HTTP request. (Which is the whole reason this proposal exists.)

- The phrasing and descriptions around closures and what scope they run in is quite confusing. It really needs better examples. Am I correct in summarizing it as "a closure inherits the scope of its callsiite, not creation site"?

- For secondary vote A (the superglobals), the example is very unclear. You're `use`ing $request and $handler, but those are never defined. It looks like you're providing no alternative API or automation; really just an under the hood separation of $_GET based on scope. While I can see the simplicity of that, it also means that basically every scope start would need to do the same copying, unless it was absolutely certain there was no code that will be run it that tries to read those superglobals. Forget to do so and poof, some legacy garbage function that reads $_POST directly now gets no data and you don't know why. This feels like a footgun.

- The first mention of $GLOBALS is in the superglobal secondary vote section. Are globals and thus $GLOBALS automatically scoped regardless? That should be clarified.

- Oh, that's mentioned further down in the "what follows scope" section. That should come way earlier. :slight_smile: I am undecided if I agree globals should not follow the scope. That feels like the sort of thing you would want to follow scope.

Overall, I think this is a promising approach. I like that it is narrowly and tightly focused. However, I am still uneasy about how narrow it is. I can see the argument for "make your own WeakMap and go away" as an approach. But I also fear that the result is we'll have a lot of subtly-different and incompatible ways of handling that (say, a multi-fiber server like AmPHP, a DI Container, and a specific service that does weird things for reasons), which could lead to hard-to-diagnose bugs. I am undecided here.

As a concrete use case that I have been actively pondering of late: At work, we have an app that switches which DB it connects to per-request, based on the Customer that is specified through the domain name. (Right now it routes through an env var to a constant, but that I could change.) That works fine in FPM mode, but would fail horribly in FrankenPHP Worker mode. Scopes seem like they're the solution to that problem, but I'm not completely clear how they'd operate in practice in that case. I wouldn't want a different DB connection to cause every service downstream from it to be recreated on every soft-request, as that eliminates the main advantage of worker mode. But the RFC examples are all doing a pseudo-global service locator, not something I am able or willing to do. (I doubt I could coax Doctrine into working that way.) So what would it looks like in a real dependency injection situation?

--Larry Garfield

On Wed, Oct 28, 2026, at 21:58, Larry Garfield wrote:

do we still want to have `run(callable, ...$args)`? `run(Closure $c)` would
work just as well

My preferred way to write it is an arrow function, which shows exactly what
runs inside the scope:

    $scope->run(fn() => doAThing(1, 2, 4));

But run(doAThing(...), 1, 2, 4) is consistent with the other core APIs:
Fiber::start(), call_user_func(), register_shutdown_function() and many
more take the same "$fn, ...$args" pair. Moving away from that pattern
seems worthy of a separate RFC, and I don't think the Scope RFC should be
the first to break ranks.

It also combines with PFA better than run(Closure $c) would:

    function func(int $a, int $b): void {}

    // run(Closure $c):
    $scope->run(fn() => func(1, 2)); // works
    $scope->run(func(1, 2, ...)); // works
    $scope->run(func(1, ...)); // fails: $b is missing

    // run(callable $c, mixed ...$args):
    $scope->run(func(...), 1, 2); // works
    $scope->run(func(1, ?), 2); // works
    $scope->run(fn() => func(1, 2)); // works

Every form that works with a closure-only run() works with this one too,
and a partial application with open parameters only works with this one.

The examples will avoid the PFA form, though, because it reads like a call,
and the difference between running code in the scope and running it before
the scope is entered is three dots:

    $scope->run(doAThing(1, 2, 4, ...)); // doAThing runs in $scope
    $scope->run(doAThing(1, 2, 4)); // doAThing runs in the caller's scope;
                                         // run() gets whatever it returned

The docblock on Scope::bind() is horribly confusing and clumsy.

Agreed, I'll rewrite it. And yes, it is the Closure::bind() idea: it wraps
a closure in an explicit scope, and returns a new closure that always runs
in that scope, whoever calls it. That is sometimes useful, for example when
the closure needs dependency injection from the scope it came from rather
than from the scope it ends up being called in.

"A scope keeps no link to the scope it was run from." So that fully
precludes getParentScope() and such, yes? What is the reason?

It's simple to add in userspace with a WeakMap<Scope, Scope>, for code that
wants a hierarchy. In core it would carry a risk of memory leaks: an app
designed to create each new scope from the previous one, millions of times,
would keep the whole chain alive.

I think you mean "PHP process" here

Under the CLI the root scope is the process, yes. Under php-fpm it is the
request, not the process, which handles many requests. I'll spell out both
cases instead of saying "request".

Am I correct in summarizing it as "a closure inherits the scope of its
callsite, not creation site"?

Yes. Closures don't have a scope; stack frames do. A closure is just code:
while it runs, some scope is current, and later the same closure can run
while another scope is current. What matters is the scope that called it,
since the scope never changes while a function's instructions are running.

Fibers and generators look different, but follow the same rule:

- A fiber gets a scope because it will get a stack frame as soon as
  $fiber->start() is called. It is bound to the scope that created it, so
  it starts in that scope, whoever starts or resumes it.

- A generator function is just a function and isn't bound to a scope. But
  a Generator is, in a sense, a stack frame: calling the function creates
  it, so the Generator object (not the generator function) is bound to the
  scope it was created in.

I'll add examples for each.

For secondary vote A (the superglobals), the example is very unclear.
[...] Forget to do so and poof

$request and $handler are the server's own; I'll make that explicit. The
copying is not something applications do. It is done once, by whatever
creates the request scope: Swerve, FrankenPHP, RoadRunner. That is the same
place that fills the superglobals today.

A new scope starting with empty superglobals is deliberate. Scopes are a
new feature, and it seems safer to start the scope's globals empty and
require frameworks to populate them, than to start them as clones of the
parent's. Clones would let a parent scope mutate values inside its child
scopes through object properties, and every framework would have to clear
them out first.

The first mention of $GLOBALS is in the superglobal secondary vote
section. [...] I am undecided if I agree globals should not follow the
scope.

I'll move that up. Globals and static properties stay shared because
applications use them for caches, registries and singletons. Warming those
once and keeping them across requests is the reason to run in worker mode
at all. If they followed the scope, every request would start cold.

However, I am still uneasy about how narrow it is. [...] I also fear that
the result is we'll have a lot of subtly-different and incompatible ways
of handling that

That is what we have today, and it's why I wrote this. I spent two years
trying to do it in userspace with phasync. phasync attaches a context to
each fiber and that context follows every child fiber. It almost works,
but not quite:

1. A generator passed from one request to another, concurrent request can
   produce one value in one fiber and the next in another. A fiber can't
   serve as identity from userspace unless developers pass an
   identification token as an argument everywhere.

2. Amp, React and phasync can each provide some identity tying code to a
   request/response pair. But then every third-party library has to pick
   one, React or Revolt or something else, integrate with it, or add an
   adapter layer. That is the incompatibility you describe, and it exists
   precisely because core has no such identity.

3. In core it is nearly free. It is fast in ext-scope and slow in
   userspace.

4. It makes superglobals less global, which has been one of the main
   criticisms of PHP for more than a decade.

5. Scope could store values, but then it could quickly become a kind of
   service locator and encourage poor design. A WeakMap keyed on Scope
   avoids naming conventions for keys, and it limits who can reach
   something like a database connection: only the code holding the map.

6. There will be bugs, but not necessarily subtle ones. When one process
   handles 5000 concurrent requests, you can't hand out 5000 PDO
   connections; you need a limit on the total and a pool. Scope doesn't
   cause that class of bug. High concurrency does, and the community will
   have to learn to work with it, as Java, C#, Node and Python did.

But the RFC examples are all doing a pseudo-global service locator, not
something I am able or willing to do. [...] So what would it look like in
a real dependency injection situation?

That's a fair objection, and the examples are to blame: I wrote them to
show the mechanism in as few lines as possible, and they ended up looking
like a service locator. I'm not proposing one, and I'll replace them with
a container example.

Scope supports the service locator pattern and dependency injection alike;
it doesn't care which one a framework chooses. I think the confusion comes
from where the scope lives. Functions and closures are not bound to a
scope, and neither is the DI container: it isn't bound to the root scope
just because it was built there. When the container is invoked, the call
goes on the stack with the current scope, so the container sees the scope
it was called from.

That lets a container offer what .NET calls a scoped lifetime: a service
that is neither a singleton shared by all requests nor a transient, but
one instance per request, shared by everything inside that request. The
container keeps those instances in a WeakMap keyed on the Scope, which
users never see.

This is how other languages do it. The runtime gives each unit of work an
identity that follows it across async boundaries, and the container, not
application code, uses it:

- .NET: AsyncLocal<T> flows with the ExecutionContext across awaits.
  Microsoft.Extensions.DependencyInjection has ServiceLifetime.Scoped,
  ASP.NET Core creates one IServiceScope per request, and the container
  can refuse a scoped service injected into a singleton (ValidateScopes).

- Java: Spring's @RequestScope and CDI's @RequestScoped. A singleton gets
  a proxy and calls it normally, and the proxy finds the current request's
  instance through a ThreadLocal (RequestContextHolder in Spring).
  ScopedValue (JEP 506) is the newer primitive for this, and works with
  virtual threads.

- Node: AsyncLocalStorage. NestJS has request-scoped providers
  (Scope.REQUEST), awilix has createScope(). TC39's AsyncContext proposal
  would put the same thing in JavaScript itself.

- Python: contextvars (PEP 567), which asyncio copies into every task.
  Async frameworks and DI libraries keep request-scoped state in it.

- Go passes context.Context explicitly as the first argument everywhere.
  That is the alternative, and it is the "identification token as an
  argument everywhere" PHP code would need without this RFC.

In none of these do classes look services up through the request
identity: they still get their dependencies through the constructor. PHP
has no such identity today, and that is all the primary vote adds.

This is 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]);
        }
    }

A singleton is built once per worker, a scoped service once per request,
and the request's services are freed with its scope, without the container
ever hearing that the request ended.

For your case, your services stay singletons and are built once per
worker. Only the connection is resolved per request, which is what
Spring's scoped proxy does:

    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)();
        }
    }

$open looks at the current request's host (from $_SERVER['HTTP_HOST']
under vote A, or the framework's request object) and connects to that
customer's database. Every service downstream depends on TenantConnection,
not on a PDO, so none of them is recreated. That is also the one rule, as
in .NET: a singleton must not keep a scoped service it got in its
constructor.

Doctrine is the one place to be careful: the EntityManager holds request
state (the identity map and the unit of work), so it has to be scoped too,
or entities leak between customers. The expensive parts, metadata, proxies
and configuration, stay shared.

If you want to see it in practice, this is a complete app for Swerve
(GitHub - phasync/swerve: SWERVE - the PHP application server · GitHub), using ext-scope's superglobals:

    <?php // swerve.php
    while (Swerve\Swerve::accept(null, function () {
        $before = $_GET['name'] ?? '-';
        usleep(500_000); // other requests run in this worker meanwhile
        $after = $_GET['name'] ?? '-';
        echo "before=$before after=$after\n";
    })) {
    }

    $ composer require phasync/swerve
    $ vendor/bin/swerve --workers=1 swerve.php

(Swerve loads the extension phasync bundles, which includes ext-scope.)

With one worker, 20 concurrent requests with ?name=req1 to ?name=req20 all
finished in 0.54 seconds, so they really overlapped. Each one printed its
own name before and after the sleep. No request object and no container:
just $_GET, which every request sees as its own.

Frode

On Wed, Oct 28, 2026, at 7:09 PM, Frode Børli wrote:

The examples will avoid the PFA form, though, because it reads like a call,
and the difference between running code in the scope and running it before
the scope is entered is three dots:

    $scope->run(doAThing(1, 2, 4, ...)); // doAThing runs in $scope
    $scope->run(doAThing(1, 2, 4)); // doAThing runs in the caller's scope;
                                         // run() gets whatever it returned

I'd request at least one example somewhere that shows using the PFA form, if only to clarify that it's legal and valid. (Whether it's optimally readable is a more subjective question I'm fine not addressing here.)

"A scope keeps no link to the scope it was run from." So that fully
precludes getParentScope() and such, yes? What is the reason?

It's simple to add in userspace with a WeakMap<Scope, Scope>, for code that
wants a hierarchy. In core it would carry a risk of memory leaks: an app
designed to create each new scope from the previous one, millions of times,
would keep the whole chain alive.

That's valid. Please include that in the RFC.

I think you mean "PHP process" here

Under the CLI the root scope is the process, yes. Under php-fpm it is the
request, not the process, which handles many requests. I'll spell out both
cases instead of saying "request".

Yeah, the terminology here is going to be tricky, but important to be extremely clear on. "request" already means a half dozen things today depending on context, so maybe it's best to avoid it where possible in the RFC?

Am I correct in summarizing it as "a closure inherits the scope of its
callsite, not creation site"?

Yes. Closures don't have a scope; stack frames do. A closure is just code:
while it runs, some scope is current, and later the same closure can run
while another scope is current. What matters is the scope that called it,
since the scope never changes while a function's instructions are running.

Fibers and generators look different, but follow the same rule:

- A fiber gets a scope because it will get a stack frame as soon as
  $fiber->start() is called. It is bound to the scope that created it, so
  it starts in that scope, whoever starts or resumes it.

- A generator function is just a function and isn't bound to a scope. But
  a Generator is, in a sense, a stack frame: calling the function creates
  it, so the Generator object (not the generator function) is bound to the
  scope it was created in.

I'll add examples for each.

Ah, so a rule of "scope is bound at stack-frame-creation-time" is a useful global rule to state explicitly, then explain how it applies to various scenarios. That would help clarify the logic, methinks.

For secondary vote A (the superglobals), the example is very unclear.
[...] Forget to do so and poof

$request and $handler are the server's own; I'll make that explicit. The
copying is not something applications do. It is done once, by whatever
creates the request scope: Swerve, FrankenPHP, RoadRunner. That is the same
place that fills the superglobals today.

A new scope starting with empty superglobals is deliberate. Scopes are a
new feature, and it seems safer to start the scope's globals empty and
require frameworks to populate them, than to start them as clones of the
parent's. Clones would let a parent scope mutate values inside its child
scopes through object properties, and every framework would have to clear
them out first.

I'm not clear how the parent scope could mutate values inside the new scope.

My concern is this sort of case:

function legacyLogic(string $message)
{
    print $message . ', ' . $_GET['name'];
}

If that is run today, it works. (It's dumb, but it works.)

However, if we do this:

new Scope()->run(legacyLogic('Hello', ...));

Then inside the scope $_GET['name'] no longer exists, so poof, it no longer works. And in a non-trivial scenario, legacyLogic() could be called 20 functions deep, so it's nearly impossible to know that it exists. It means as the scope creator I need to always do something like this, just in case:

$get = $_GET;
$post = $_POST;
$request = $_REQUEST;
$server = $_SERVER;
new Scope()->run(function () use($get, $post, $request, $server) {
    $_GET = $get;
    $_POST = $post;
    $_REQUEST = $request;
    $_SERVER = $server;
    legacyLogic('hello');
});

Needing to write lots of boilerplate like that "just in case" is a red flag in my mind. Moreover, if the secondary vote doesn't pass initially but is introduced in some later version, it becomes a BC break for anything using a superglobal that happens to be called from within a scope, something the function (by design) doesn't know.

Not cloning feels like a footgun. I would think initializing with a clone of the parent scope and letting the scope setup code modify it if desired would be the safer option, and require less work.

The first mention of $GLOBALS is in the superglobal secondary vote
section. [...] I am undecided if I agree globals should not follow the
scope.

I'll move that up. Globals and static properties stay shared because
applications use them for caches, registries and singletons. Warming those
once and keeping them across requests is the reason to run in worker mode
at all. If they followed the scope, every request would start cold.

That's a valid argument, but both are also frequently used for request-specific caches today. (Global current user, or a static cache that derives from request-sensitive data, etc.) Those would suddenly become buggy if there's multiple scopes happening and the code isn't prepared for it.

Thought: Would a `scoped` keyword on a static property or global (maybe just static property) be useful, to easily separate that data by scope rather than needing to reengineer it to use a WeakMap? Basically automating the WeakMap logic.

I suppose that wouldn't help with BC anymore than telling people to use getCurrent() would, but it's something. BC would require doing it via an attribute, and I don't know if there's appetite for that.

Something like:

class Foo {
    #[Scoped]
    private static $cache;

    public function getFoos() {
        return $this->cache ??= $this->computeFoosRequestSensitive();
    }
}

Which simply automates the WeakMap logic that everyone would need to replicate anyway, while also being backward compatible with existing code.

Other thought: We already have a magic syntax for "the current object scope": $this. Would it make sense to have some other first-class syntax for Scope::getCurrent() that is more compact and self-descriptive? $scope almost certainly wouldn't work for BC reasons, but maybe a keyword?

However, I am still uneasy about how narrow it is. [...] I also fear that
the result is we'll have a lot of subtly-different and incompatible ways
of handling that

That is what we have today, and it's why I wrote this. I spent two years
trying to do it in userspace with phasync. phasync attaches a context to
each fiber and that context follows every child fiber. It almost works,
but not quite:

I'm sold on the use case, and the more I think about it the more sold I am. It's more that I'm torn on this point:

5. Scope could store values, but then it could quickly become a kind of
   service locator and encourage poor design. A WeakMap keyed on Scope
   avoids naming conventions for keys, and it limits who can reach
   something like a database connection: only the code holding the map.

which is a concern I completely share! I don't think $scope->attributes['good luck keeping these straight'] is the right answer either. My concern is if everyone needs to write their own WeakMap routines, it is very likely that at least a third of them will be subtly wrong in some way. The #[Scoped] attribute above might go a long way to mitigating that concern, but it requires some more consideration.

Also, if we just "magically" separate the superglobals or locale or timezone or whatever, it's not obvious that something has been separated. As the list of things that are separated grows with future RFCs, that could introduce subtle behavior breaks that only show up when code is used in a scope, as in the $_GET example above.

6. There will be bugs, but not necessarily subtle ones. When one process
   handles 5000 concurrent requests, you can't hand out 5000 PDO
   connections; you need a limit on the total and a pool. Scope doesn't
   cause that class of bug. High concurrency does, and the community will
   have to learn to work with it, as Java, C#, Node and Python did.

That's going to be fun to deal with... Are there good examples we can point to to help PHP collectively wrap its head around that pattern faster?

In none of these do classes look services up through the request
identity: they still get their dependencies through the constructor. PHP
has no such identity today, and that is all the primary vote adds.

This is 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);
        }

This is the sort of code I fear everyone doing slightly differently and half of us getting it slightly wrong.

If I understand correctly, it would also then be incumbent on the container to ensure that a service that depends on a scoped service is itself scoped. If it doesn't, that sounds like Weird Things(tm) could happen. (As in my database example below.)

        public function has(string $id): bool
        {
            return isset($this->services[$id]);
        }
    }

A singleton is built once per worker, a scoped service once per request,
and the request's services are freed with its scope, without the container
ever hearing that the request ended.

For your case, your services stay singletons and are built once per
worker. Only the connection is resolved per request, which is what
Spring's scoped proxy does:

    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)();
        }
    }

$open looks at the current request's host (from $_SERVER['HTTP_HOST']
under vote A, or the framework's request object) and connects to that
customer's database. Every service downstream depends on TenantConnection,
not on a PDO, so none of them is recreated. That is also the one rule, as
in .NET: a singleton must not keep a scoped service it got in its
constructor.

Doctrine is the one place to be careful: the EntityManager holds request
state (the identity map and the unit of work), so it has to be scoped too,
or entities leak between customers. The expensive parts, metadata, proxies
and configuration, stay shared.

So the way to do it would be to have a non-scoped factory layer that implements the Connection interface (and a second one that implements the EntityManager interface) and passes all requests on to a scope-sensitive instance. And the factory would need to be externalized so that it could check the current scope itself? Something like:

class ConnectionProxy implements ConnectionInterface {
    private WeakMap $conns;

     public function __construct(private Closure $open) {}

    public function executeQuery(string $q, array $args) {
        $this->getScopedConn()->executeQuery($q, $args);
    }

    private function getScopedConn() {
        return $this->conns[Scope::getCurrent()] ??= ($this->open)();
    }
}

$conn = new ConnectionProxy(function () {
    $domain = $_SERVER['domain'];
    // Logic to pick the DB here.

    return DriveManager::getConnection(blah);
});

Give or take the pool management you mentioned before.

This is what I'm concerned about. That looks tricky to get right. Eg, it looks like I totally forgot to manually initialize the WeakMap in the constructor. But I suspect this pattern will be common, not just for databases but also for any user-specific objects that get created, like a connection to someone's Mastodon account or whatever. So this is a pattern we need to work to make as fool-proof as possible, because we're all fools. :slight_smile:

Continuing my brainstorming from above:

class ConnectionProxy implements ConnectionInterface {
    #[Scoped]
    private Connection $conn;

     public function __construct(private ConnectionMaker $open) {}

    public function executeQuery(string $q, array $args) {
        ($this->conn ??= $this->open())->executeQuery($q, $args);
    }
}

class ConnectionMaker {
    public function __invoke() {
        $domain = $_SERVER['domain'];
        // Logic to pick the DB here.
        return DriveManager::getConnection(blah);
    }
}

That's still not ideal, but has notably fewer moving parts to screw up.

Though thinking about it, passing a PSR-7 request object to the ConnectionMaker would make it not scope-sensitive; It would *have* to work through the superglobals, or some other global call to get a request object. I'm seeing turtles all the way down here, which has me nervous.

As I said, still in favor of the concept, but I want to make sure we go down these rabbit holes to ensure the turtles don't get too deep. (Boy that's an abused metaphor...)

--Larry Garfield

On 26/10/2026 16:03, Frode Børli wrote:

Hi internals,

I'd like to start the discussion on a new RFC:

PHP: rfc:scope

Hi Frode,

I'm really happy to see this as an independent, focussed, RFC, which can hopefully fit well with the other async-related proposals being worked on.

In early versions of the "True Async" RFC, Edmond Dantes included a complex API for attaching data to coroutine scopes, and I argued at the time that it could be simplified, and more complex structures built on top of it later. It looks like that's exactly the approach taken here, providing only the parts that are essentially impossible in userland.

I do share Larry's concern that some of the common patterns using WeakMap will be hard to get right, but maybe that can be solved by additional helper classes and functions which might have other uses anyway?

The only slightly trivial reaction I had was to the name: variable scope is something we talk about so often, that I can see "variables tied to the current Scope" confusing people. Naming things is notoriously hard, but I note that a lot of the other languages you reference use the word "context" instead, and wonder if you'd considered that?

Thanks,

--
Rowan Tommins
[IMSoP]

I did go back and forth with terminology, but eventually landed on Scope. The term is used elsewhere in php documentation, for example Closure::bind() etc, but context is used much more.

fiber-interop/api on packagist has a Scope polyfill, and I don’t think personally that WeakMap was hard to get right for scoped services. It takes getting used to, but it seems better than storing data directly in the scope object.

With regards,
Frode Børli

Sendt fra Outlook for iOS

···

From: Rowan Tommins [IMSoP] imsop.php@rwec.co.uk
Sent: Sunday, 01 November 2026 15:26:40
To: internals@lists.php.net internals@lists.php.net
Subject: Re: [PHP-DEV] [RFC] Scope

On 26/10/2026 16:03, Frode Børli wrote:

Hi internals,

I’d like to start the discussion on a new RFC:

https://wiki.php.net/rfc/scope

Hi Frode,

I’m really happy to see this as an independent, focussed, RFC, which can hopefully fit well with the other async-related proposals being worked on.

In early versions of the “True Async” RFC, Edmond Dantes included a complex API for attaching data to coroutine scopes, and I argued at the time that it could be simplified, and more complex structures built on top of it later. It looks like that’s exactly the approach taken here, providing only the parts that are essentially impossible in userland.

I do share Larry’s concern that some of the common patterns using WeakMap will be hard to get right, but maybe that can be solved by additional helper classes and functions which might have other uses anyway?

The only slightly trivial reaction I had was to the name: variable scope is something we talk about so often, that I can see “variables tied to the current Scope” confusing people. Naming things is notoriously hard, but I note that a lot of the other languages you reference use the word “context” instead, and wonder if you’d considered that?

Thanks,

-- 
Rowan Tommins
[IMSoP]

Hi Larry,

Thanks for going through it in this much detail. I've updated the RFC to 0.9.5 with the clarifications you asked for:

- the rule that a scope is bound when a call, fiber or generator is created;
- why a scope has no parent link;
- a run() example with partial application;
- statics and $GLOBALS mentioned in the introduction.

The proposal itself is unchanged.

On superglobals starting empty: your legacyLogic() example breaks because it creates a scope. Code that should see the current request doesn't need to: it already runs in the request's scope, and so does every fiber it starts. You create a scope when you start a new unit of work, in practice a new request inside a long-running server. If a new scope inherited its creator's arrays, the server would have to clear them for every request, and one it missed would leak into the next request. A copy would also be shallow: an object stored in $_REQUEST or $_SESSION would be the same instance in both scopes.

On request data in statics: that code is already wrong under FrankenPHP's worker mode, RoadRunner and Swoole, whether or not this RFC passes. Scope doesn't make it wrong; it gives that code a key to move the data to.

On the WeakMap boilerplate: I see scoped services as the container's job. Most application code never touches Scope. The server creates the scopes, and the container keys its scoped services by them, as ASP.NET Core's container and Spring's scoped proxies do. Your ConnectionProxy is that pattern, written once in the container or the DBAL rather than in every application. I've mentioned an attribute like #[Scoped] under Future Scope, for when containers have settled on a common pattern.

On the turtles: they stop at the server. It creates the request's scope and puts the request into it, through $_SERVER under vote A or through the framework's own request holder keyed by the scope. Your ConnectionMaker reads it from there, and everything above it stays a singleton.

On a keyword: I'd rather not. Outside containers and servers, Scope::getCurrent() should be rare.

Places to point people to: .NET's AddScoped() with IServiceScopeFactory, Spring's @RequestScope with scoped proxies, Python's contextvars and Node's AsyncLocalStorage.

Best regards,
Frode Børli

Hello,

Le jeudi 29 octobre 2026, 13:22:04 heure normale d’Europe centrale Larry Garfield a écrit :

Needing to write lots of boilerplate like that "just in case" is a red flag in my mind. Moreover, if the secondary vote doesn't pass initially but is introduced in some later version, it becomes a BC break for anything using a superglobal that happens to be called from within a scope, something the function (by design) doesn't know.

I had the same question reading the RFC, how can the future scope be implemented without BC break?
If suddenly scope starts to clear headers, ini_set or whatever, all existing code using it will break?
Can you explain how future extension of what gets scoped can be achieved without BC break?

Côme

Hi Côme,

If suddenly scope starts to clear headers, ini_set or whatever, all existing code using it will break?

Nothing is cleared, in this RFC or in a later one. When a piece of state follows the scope, each scope has its own instance of it. The root scope keeps the process state exactly as it is today, so code that never creates a scope, which is all code written before this RFC, sees no change, now or later.

Code that runs inside a non-root scope is also meant to keep working as it does today. That is one of the purposes of Scope: legacy code should keep working in a long-running server without being rewritten. Take vote B: code that calls Locale::setDefault() for user X and later Locale::getDefault() does so within one request, and both calls happen in the same scope, so it gets the locale it set. What changes is that a request for user Y, running in another scope, no longer sees X's locale. From the point of view of the code, nothing changed; it just stopped being affected by other requests.

The reason this holds is where scopes are switched. Code does not switch scope while it is processing one request. Scopes are switched between requests, by the SAPI or the application server, which is also the party that has the request to put into the new scope. The parallel work a request starts stays in the request, through fibers, which follow the scope. Larry's legacyLogic() example creates a scope in the middle of a request and then expects the request's data to still be there; that is not what run() is for, and I'll make that more explicit in the RFC.

Each later move is still its own RFC, with its own BC section and vote; the Future Scope list states the direction, so that servers and frameworks creating scopes know it before they write that code. What this RFC fixes now is the rule they would all follow: a scope has its own instance of the state that follows it, and the root keeps what the process has today.

Best regards,
Frode Børli

Le mardi 10 novembre 2026, 13:46:42 heure normale d’Europe centrale Frode Børli a écrit :

Nothing is cleared, in this RFC or in a later one. When a piece of state follows the scope, each scope has its own instance of it. The root scope keeps the process state exactly as it is today, so code that never creates a scope, which is all code written before this RFC, sees no change, now or later.

Code that runs inside a non-root scope is also meant to keep working as it does today. That is one of the purposes of Scope: legacy code should keep working in a long-running server without being rewritten. Take vote B: code that calls Locale::setDefault() for user X and later Locale::getDefault() does so within one request, and both calls happen in the same scope, so it gets the locale it set. What changes is that a request for user Y, running in another scope, no longer sees X's locale. From the point of view of the code, nothing changed; it just stopped being affected by other requests.

The reason this holds is where scopes are switched. Code does not switch scope while it is processing one request. Scopes are switched between requests, by the SAPI or the application server, which is also the party that has the request to put into the new scope. The parallel work a request starts stays in the request, through fibers, which follow the scope. Larry's legacyLogic() example creates a scope in the middle of a request and then expects the request's data to still be there; that is not what run() is for, and I'll make that more explicit in the RFC.

Each later move is still its own RFC, with its own BC section and vote; the Future Scope list states the direction, so that servers and frameworks creating scopes know it before they write that code. What this RFC fixes now is the rule they would all follow: a scope has its own instance of the state that follows it, and the root keeps what the process has today.

I have to say this answer does not resolve my worry. For code that will be written once the RFC is accepted, it will get broken if a future RFC adds things to what follow the scope.
I understand that «Each later move is still its own RFC, with its own BC section and vote», but to me that means that nothing will be able to be changed later to follow the scope, as that would be too big of a BC break.

Côme

On Tue, Nov 10, 2026, at 6:46 AM, Frode Børli wrote:

Hi Côme,

If suddenly scope starts to clear headers, ini_set or whatever, all existing code using it will break?

Nothing is cleared, in this RFC or in a later one. When a piece of
state follows the scope, each scope has its own instance of it. The
root scope keeps the process state exactly as it is today, so code that
never creates a scope, which is all code written before this RFC, sees
no change, now or later.

Code that runs inside a non-root scope is also meant to keep working as
it does today. That is one of the purposes of Scope: legacy code should
keep working in a long-running server without being rewritten. Take
vote B: code that calls Locale::setDefault() for user X and later
Locale::getDefault() does so within one request, and both calls happen
in the same scope, so it gets the locale it set. What changes is that a
request for user Y, running in another scope, no longer sees X's
locale. From the point of view of the code, nothing changed; it just
stopped being affected by other requests.

The reason this holds is where scopes are switched. Code does not
switch scope while it is processing one request. Scopes are switched
between requests, by the SAPI or the application server, which is also
the party that has the request to put into the new scope. The parallel
work a request starts stays in the request, through fibers, which
follow the scope. Larry's legacyLogic() example creates a scope in the
middle of a request and then expects the request's data to still be
there; that is not what run() is for, and I'll make that more explicit
in the RFC.

Each later move is still its own RFC, with its own BC section and vote;
the Future Scope list states the direction, so that servers and
frameworks creating scopes know it before they write that code. What
this RFC fixes now is the rule they would all follow: a scope has its
own instance of the state that follows it, and the root keeps what the
process has today.

Best regards,
Frode Børli

I think there's an implicit assumption you're making here that is not safe to make.

Specifically, you're focused on the request scope use case. I agree, that's the most obvious place for it to apply, and the likely most common. And the 2-3 libraries that make a request scope (FrankenPHP, Revolt, Swoole, etc.) that other people build off of can probably be expected to get it right (for whatever "right" means).

However, there is nothing in the design of the RFC that limits it to being used just for the request, and only by a select number of very careful projects. It can be created by literally anyone, anywhere, at any time, whether we think it's a good idea or not. Which means I can guarantee it *will* be created by someone, somewhere, at some time that is bad idea, and sloppily.

So literally any function that reads the super globals today *could* end up in a scope created by someone other than FrankenPHP that doesn't manually clone the superglobals, and therefore will break. That it's not a responsibly created request-bound scope is irrelevant, because not all scopes will conform to that lifecycle.

The same applies for any other "ambient state" that becomes scope-aware. If the pattern is that a new Scope starts with a blank ambient state, and it's the caller's job to populate it, then every time new parts of the ambient state become scope-aware, the required manual setup code changes. That creates a BC break every single time more ambient state is added. That simply won't fly.

Instead, if the scope-aware ambient state starts as a clone of the originating scope, then in most cases code doesn't care. That it's now working with a copy of $_GET, or a scope-bound default locale, or scope-bound default timezone is irrelevant in the 99% case. But it shouldn't have to deal with "whelp, someone made a new scope 40 function calls up the stack, so now the ambient state is missing." Missing ambient state is a fatal waiting to happen.

Even then, there's still a small BC concern if some existing code is setting the ambient state, and expecting it to persist for the entire process lifetime instead of just the current scope lifetime. However, the surface area for that is orders of magnitude smaller than "All code needs to consider that $_GET might not be set at all now, sorry."

This is a landmine large enough that it would keep me from supporting this RFC, which I otherwise quite like.

--Larry Garfield

Hi Larry, Côme,

Thanks for pressing on this; I'd rather fix it in the RFC than find it
in the vote.

One clarification first, because I think it narrows the problem: a scope
only affects the code that runs inside it, and the only one who can run
your function inside a scope is a caller of yours. That caller can
already clear $_GET before calling you and restore it after, or change
the default timezone for the duration of the call. A scope gives them
nothing they could not do today, except that what the inner code changes
cannot leak back out. So "someone created a scope 40 calls up the stack"
has the same blast radius as "someone cleared the superglobals 40 calls
up the stack": a bug in that caller, not a new way for code to run with
state it was not given.

What that leaves, and what I take from both of you, is that there are
two reasons to create a scope and the RFC only serves one. A server
creates a scope to start a new unit of work, and there starting empty is
right. A test, a plugin host or a sandbox creates a scope to guard the
current state from the inner code, and there the inner code should see
what the creator sees, now and after any later RFC adds to what follows
the scope. I intend to add that second case: a scope that starts as a
copy of its creator's request arrays and current locale and timezone, so
that code which guards inherits, and a later move changes only what
"fresh" means, which concerns the servers.

Before I write it up I'd like your view on the shape of it. Should
inherit be the default of new Scope(), with the servers asking
explicitly for a fresh one, or the other way around? Is a shallow copy
of the arrays what you'd expect, or should the inherited scope share
them with its creator? And is there anything else in the "missing
ambient state" category that you'd want covered by the same rule?

Best regards,
Frode Børli

Hi Larry, Côme, Rowan, Kévin,

A question of direction, since all of you have touched it from different
sides.

The RFC today is deliberately the small end of something we know the
full size of: Swerve (0.2, in release candidates) runs concurrent
requests on top of the CLI SAPI with all of it isolated per request,
through ext-scope and the phasync extension. Beyond the superglobals,
the session, the locale and the timezone that the RFC covers, that means
the whole of the request info (method, URI, query string, content type
and length, cookies, auth), the request body and uploaded files,
filter's raw input, REQUEST_TIME, and on the output side the
output-buffer stack, zlib's compression state, the header list with
headers_sent and the header callback, connection_status, and the
shutdown functions. The output half is not just state to swap: it needs
a per-request sink, which means a request/response contract that the
server implements, with write, read, send headers and flush. Error
handlers, ini_set() values, the last-error functions, setlocale(),
chdir(), statics and $GLOBALS stay shared in that design too.

Two ways to get there from here:

1. Minimal, then opt in over time. Scope is an identity, and isolation
is requested per concern with a bitmask, new Scope(isolate:
Scope::REQUEST | Scope::TIMEZONE); an isolated concern starts fresh, an
unisolated one is shared with the creator, and the engine gives core and
extensions enter/leave hooks per bit so each owns its part. Later RFCs
add bits; code that never asked for a bit is never affected by it, which
I think answers both Larry's landmine and Côme's question. Scope::ALL
means everything this version can isolate and grows like E_ALL. This RFC
would define the mechanism and the first bits.

2. All in. The same mechanism, plus the request and response contract
and the input/output bits, in one RFC. It is the complete picture, and
it is the concurrent counterpart of Kévin's request lifecycle hooks, so
the two could be designed together. It is also a much larger jump, and a
much larger discussion.

I am not against the second; I started small because the first step is
the one that has to be in the engine, and the rest can follow once it is
in. But if you would rather see the whole shape before voting on any of
it, I'd rather hear that now than after the vote opens.

Best regards,
Frode Børli

On Wed, Nov 11, 2026, at 10:04 AM, Frode Børli wrote:

Hi Larry, Côme,

Thanks for pressing on this; I'd rather fix it in the RFC than find it
in the vote.

One clarification first, because I think it narrows the problem: a scope
only affects the code that runs inside it, and the only one who can run
your function inside a scope is a caller of yours. That caller can
already clear $_GET before calling you and restore it after, or change
the default timezone for the duration of the call. A scope gives them
nothing they could not do today, except that what the inner code changes
cannot leak back out. So "someone created a scope 40 calls up the stack"
has the same blast radius as "someone cleared the superglobals 40 calls
up the stack": a bug in that caller, not a new way for code to run with
state it was not given.

What that leaves, and what I take from both of you, is that there are
two reasons to create a scope and the RFC only serves one. A server
creates a scope to start a new unit of work, and there starting empty is
right. A test, a plugin host or a sandbox creates a scope to guard the
current state from the inner code, and there the inner code should see
what the creator sees, now and after any later RFC adds to what follows
the scope. I intend to add that second case: a scope that starts as a
copy of its creator's request arrays and current locale and timezone, so
that code which guards inherits, and a later move changes only what
"fresh" means, which concerns the servers.

Before I write it up I'd like your view on the shape of it. Should
inherit be the default of new Scope(), with the servers asking
explicitly for a fresh one, or the other way around? Is a shallow copy
of the arrays what you'd expect, or should the inherited scope share
them with its creator? And is there anything else in the "missing
ambient state" category that you'd want covered by the same rule?

Best regards,
Frode Børli

Just to make sure we're talking about the same thing, let me offer a more concrete and realistic example.

Older frameworks very often had something like this:

function show_flash_messages() {
  if ($_GET['show'] === 1) {
    foreach ($_SESSION['flash'] ?? [] as $msg) {
      print "<p>$msg</p>\n";
    }
    $_SESSION['flash'] = [];
  }
}

Modern frameworks tend to have additional layers built on top, but they all eventually bottom out to essentially that logic. (OK, the $_GET is a bit contrived for this example, bear with me.)

Assuming a request scope created by a persisted process server (Swerve, FrankenPHP, Swoole, etc), it's probably a safe bet that $_GET and $_SESSION have been cloned, reset, or otherwise setup "properly," for some definition of properly. That means this pre-scope-era code continues to work.

My concern is when anyone else creates a Scope (whether we think they should or not), and then calls a function chain that ends up calling show_flash_messages(). That person didn't bother to set up $_GET and $_SESSION, because they didn't even realize show_flash_messages() would be called. So now what happens?

My point is that it should still continue to work, as close as possible to were there no scopes involved. To me, cloning all ambient state first, and then letting the person setting up the scope decide what to override, seems like the safest default. Simply inheriting and using the creator's values (so that modifying $_GET inside the scope does impact outside the scope) seems unwise to me. That's a great way for changes to leak unexpectedly. And I'm not entirely sure what the use case is for starting a scope "empty", but perhaps that exists. So I would default to a shallow clone of the ambient state, so that changes do not escape but code that relies on the ambient state that isn't scope-aware still works. Whether the other two options have enough of a use case to be opted-in to, I'm not sure.

I'll address the "missing ambient state" part in reply to your other email.

--Larry Garfield

On Wed, Nov 11, 2026, at 10:48 AM, Frode Børli wrote:

Hi Larry, Côme, Rowan, Kévin,

A question of direction, since all of you have touched it from different
sides.

The RFC today is deliberately the small end of something we know the
full size of: Swerve (0.2, in release candidates) runs concurrent
requests on top of the CLI SAPI with all of it isolated per request,
through ext-scope and the phasync extension. Beyond the superglobals,
the session, the locale and the timezone that the RFC covers, that means
the whole of the request info (method, URI, query string, content type
and length, cookies, auth), the request body and uploaded files,
filter's raw input, REQUEST_TIME, and on the output side the
output-buffer stack, zlib's compression state, the header list with
headers_sent and the header callback, connection_status, and the
shutdown functions. The output half is not just state to swap: it needs
a per-request sink, which means a request/response contract that the
server implements, with write, read, send headers and flush. Error
handlers, ini_set() values, the last-error functions, setlocale(),
chdir(), statics and $GLOBALS stay shared in that design too.

Two ways to get there from here:

1. Minimal, then opt in over time. Scope is an identity, and isolation
is requested per concern with a bitmask, new Scope(isolate:
Scope::REQUEST | Scope::TIMEZONE); an isolated concern starts fresh, an
unisolated one is shared with the creator, and the engine gives core and
extensions enter/leave hooks per bit so each owns its part. Later RFCs
add bits; code that never asked for a bit is never affected by it, which
I think answers both Larry's landmine and Côme's question. Scope::ALL
means everything this version can isolate and grows like E_ALL. This RFC
would define the mechanism and the first bits.

2. All in. The same mechanism, plus the request and response contract
and the input/output bits, in one RFC. It is the complete picture, and
it is the concurrent counterpart of Kévin's request lifecycle hooks, so
the two could be designed together. It is also a much larger jump, and a
much larger discussion.

I am not against the second; I started small because the first step is
the one that has to be in the engine, and the rest can follow once it is
in. But if you would rather see the whole shape before voting on any of
it, I'd rather hear that now than after the vote opens.

Best regards,
Frode Børli

Proper sizing of an RFC is a hotly debated topic, and if you ask 5 core devs you'll get 12 different answers. :slight_smile:

My own stance is that you should at the very least design the "full picture," even if you break it up into pieces to implement. For example, the aviz and property hooks RFCs were designed and written together, and some syntax choices in one were essentially dictated by the knowledge that we were planning to have the other. That meant that the two features "clicked together" much more naturally, even though we split it into two RFCs that could both justify themselves. (Whereas properties on interfaces didn't really make any sense on their own, unless accompanied by aviz and/or hooks, so we didn't split that off.)

In this case, for example, by my count you list 21 pieces of ambient state that need to be addressed for the full picture. So if they're all opt-in, that means we have 21 different bit flags (22 if you count ALL) to opt into. That seems... problematic, just from a DX perspective. Some of them may be coupled together as a single flag, but it's still a big list. So, knowing that the list is large, designing it as a piecemeal opt-in seems like a poor design, particularly since, eventually, the intent is that most code will want to use everything, meaning most scope calls will need to throw in the ALL flag, even if by then that should be the default.

So I think a key question to ask is, IF we add more ambient state over time, what is the impact on existing code? (This relates back to my previous email.) Suppose, for example, we have a class written against a minimal implementation that is just the core scope object and the HTTP superglobals, which in turn calls legacy code from before scopes exist that uses the HTTP superglobals. Now we add the default timezone to the ambient state that a scope isolates. What's the fallout? My thinking is that if the ambient state always clones, then the fallout is near-zero. If that class has a `new DateTime()` in it, and the scope class it happens to be running in never mentions the default timezone, then it will get a copy of the default timezone and nothing changes.

If it tries to reset the default timezone, then the behavior changes as the new value only persists as long as the scope. But that's literally the point, so that seems OK to me.

So it feels to me (as I am thinking aloud) that "always clone ambient state" would allow us to transparently add more things to the list of affected ambient state in future RFCs without disruption, which would lead to nice small RFCs that people like. However, I may be wrong in my assumption that it would "just work", particularly as relates to the output state. So thinking through and planning out what the output state impact would be if added separately in a follow up is a worthwhile exercise, which will both give you the design of that feature in the future and help inform if it even can be in the future or not.

Another possibility is to design and vote at once but implement in chunks. Eg, there's no RFC for every resource that gets converted to a normal object, because the decision was accepted years ago that we would do it as possible, so it's been done as-possible. It may be viable to include in the initial RFC a complete list of everything that will, eventually, get scope-bound, but explicitly say that it will dribble in over time via many PRs. That may be a good way to simplify the process rather than having 21 separate RFCs, which just from a process POV will take years and I don't think benefits anyone. (Core maintainers like Ilija and Arnaud are free to tell me to shut up on this point if they disagree with this approach.)

--Larry Garfield

Hi Larry,

Thanks, both mails land. You have changed my mind on the default, and I
have updated the RFC to 0.10 accordingly.

A new scope now starts as a copy of its creator's state, for everything
that follows the scope: the six request arrays, the session, and under
vote B the default locale and timezone. The copy is PHP's copy of an
array, so nothing is duplicated until one side writes, and from then on
the two scopes are independent. Your show_flash_messages() sees the
$_GET and $_SESSION its caller saw, and what it changes stays inside the
scope.

I went one step further than you suggested and left out the opt-out. A
server that starts a request wants a fresh set, but it 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 open, so the copy is as good as empty, and the server fills the six
as it does today. Anyone who wants a scope emptier than its creator's
can clear what they do not want to pass on. Defining an "empty" option
would mean defining what empty means for each kind of state, now and in
every later RFC, which is exactly the per-concern work the copy rule
avoids. And it can be added later without breaking anything, so leaving
it out costs nothing now.

That also answers your point about future additions, and Côme's about
moving things later. With the copy rule, a later RFC that adds, say,
ini_set() values changes nothing for code that only reads them inside a
scope; code that sets them gets containment, which is the point. So the
bitmask is gone, and "a new scope starts empty" with it.

Two places where "copy" needed spelling out, which 0.10 does. The
session: a scope constructed while a session is active holds the same id
and status and a copy of $_SESSION; it does not open the session again,
so a locking handler's lock is not taken twice, and a write-close in the
copy writes under that id while the creator's later write-close wins,
the same as keeping a copy of $_SESSION in a variable and restoring it.
And output, which you flagged: headers and the body are not values to
copy. A header set inside a scope must still reach the one response the
request has, so they are a sink the creator supplies, by default its
own, not state the copy rule can carry. That is why they need the
integration points listed under Future Scope rather than a vote here,
and I think it also answers whether they can be added later: yes, by
that mechanism, and the copy rule does not stand in the way.

On listing everything that will eventually follow the scope and voting
on it once: I am not against it, and the copy rule is what makes it
possible without the 21 flags. Future Scope in 0.10 now says that list
is the full picture this RFC is the first step of. Whether the vote
should cover the list as a commitment, as with the resource-to-object
conversion, I would like to hear from the core maintainers before
restructuring the votes.

0.10 goes on the wiki today, with a changelog entry; the extension's
next release implements the copy, its current one still starts empty.

Best regards,
Frode Børli