Hey Manuel,



On Sun, Aug 9, 2020, 11:02 Manuel Canga <p...@manuelcanga.dev> wrote:

> Hi Internals,
>
> I'd like to open up a discussion around the implementation of a new
> functionality: 'import of variables'.
>
> 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 ).
>
> I think the best is a example:
>
> ```php
> <?php
>
> $a = 1;
> $b = 2;
> $c = 3;
>
> include __DIR__.'/without_import.php';
> include __DIR__.'/all_import.php';
> include __DIR__.'/none_import.php';
> include __DIR__.'/some_vars.php';
> include __DIR__.'/global_in_function.php';
> ```
>
> ## without_import.php
>
> ```php
> <?php
>
> echo $a; //1
> echo $b; //2
> $c = 'any value'; //replace value in global var
> ```
>
> ## all import.php
>
> ```php
> <?php
>
> use vars all;
>
> echo $a; //1
> echo $b; //2
> $c = 'other value'; //replace value in global var
> ```
>
> ## none_import.php
>
> ```php
> <?php
>
> use vars none;
>
> echo $a; //Warning: undefined var $a
> echo $b; //Warning: undefined var $b
> $c = 'other value'; //assign value to local var
> ```
>
>
> ## some_vars.php
>
> ```php
> <?php
>
> use vars $a, $c, $d; //Warning: undefined var $d
>
> echo $a; //1
> echo $b; //Warning: undefined var $b
> $c = 'a value'; //replace value in global var
> ```
>
> ## global_in_function.php
>
> ```php
> <?php
>
> use vars $a, $c;
>
>
> function hello() {
>         global $a, $b, $c;
>
>         echo $a; //1
>         echo $b; //null.
>         $c = 'end value'; //replace value in global var
> }
>
> hello();
> ```
>
>
> In a project with a lot of global vars( like WordPress ) this
> functionality avoids conflicts and easy replacements of values in main
> global vars.
>

This looks like what IIFE do already (you can use them today):

```php

require 'something/with/side/effects.php';

(static function () use ($a, $b, & $c) : void {
    echo $a; //1
    echo $b; //Warning: undefined var $b
    $c = 'a value'; //replace value in global var
})();
```

You can use this right now, and it has the advantage of reporting any
missing symbols right at the time at which the closure is declared.

I tend to use IIFE all the time in procedural code, since they prevent
leaking state into globals 👍

>

Reply via email to