Hi Internals,

> This functionality would allow to create a new  'use vars' keyword in order 
> to can use( or cannot use )  global variables in local scope( of current file 
> ).

To be clear: The variables in the top-level scope depend on what has 
require()d/include()d a file.
The top-level scope starts off as being global, but if a file is required from 
within a function/method/closure (e.g. the autoloader closure), then the 
top-level scope in the require()'d file uses variables (e.g. $this) from 
whatever context called require().

It may be possible to use a declare syntax, e.g. declare(used_variables='all') 
for `'all'`, `null`, `['var1', 'var2']`, etc.
- Otherwise, you face the issue of where `use vars` should be allowed, what 
happens if there's a statement before `use vars`, etc.

I can see this as having some use cases, such as in configuration files or 
files used for bootstrapping.
For example,

```
<?php
declare(used_variables=null);

$api_base = IS_PRODUCTION ? 'https://example.com/api/' : 'http://localhost/api';
do_stuff();

return [
    // long config array
    'url_new' => "$api_base/new",
    'url_all' => "$api_base/all",
];
```

This feature (ignoring the question of syntax) would ensure that people reading 
the file knew that $api_base was not modified by other files
and that other files did not read local variables created within a 
configuration/bootstrapping file in unexpected ways,
which is a fairly common issue in some web apps I've worked on.
Opcache would also do a better job at optimizing code if it knew which 
variables in a top-level scope couldn't be modified.

That being said, there's been opposition to extensions to the language that add 
functionality that can be implemented in other ways, as in Rowan's comment,
but peoples opinions depend on the specifics of the proposal
(e.g. `match` was added and was more performant than chained conditionals or 
switch).

As Rowan said, there are ways to reimplement this:
- Wrapping the config file or bootstrapping file in a closure, global function, 
or class method
- `function safe_require_once(string $path, $vars = []) { extract($vars); 
require($path); }` from the caller, to limit what variables are passed in. 
IDEs/tooling would be worse at telling you if a file name had a typo, though.

Regards,
- Tyson
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to