Hi Mike,

> What I would rather see are new features in PHP that encourage developer
> to break functionality into shorter and simpler functions and methods, and to 
> minimize nesting.

I would also like to see shorter functions in general, but:

- Other developers may prefer long functions/scripts despite my preferences,
  but their code would still benefit from readability by having block-scoped 
variables enforced by the compiler
- Some problem domains are complex (e.g. business logic) and require a lot of 
variables,
  leading to long functions/scripts, and trying to split them up may be 
error-prone
  or cause awkward divisions of functionality.
- Even in short functions of a few dozen lines, it may be useful to know if 
reused variables such as
  `$i` are definitely scoped to a loop, when reviewing code.

> There is also an issue with block scoping that is reasonably well-known
> among the GoLang community called variable shadowing
> and that is a developer seeing a variable in block scoping
> and thinking they are accessing or assigning the function-scoped variable.

Variable shadowing is also an issue in JavaScript.
While JavaScript and GoLang don't allow introspection of the variable scope
(as far as I know, not sure about reflection),
PHP does allow dynamic access by name ($$var, `get_defined_variables()['var']` 
in a require()d file, XDebug),
and any proposal for block scoping in PHP will need to account for that somehow.

- Aside: Personally, I set up linting for golang projects to forbid shadowing.

My best plan for dealing with variable shadowing in PHP was to forbid it 
entirely,
which I mentioned examples of in the proposal.

> {
>    let $outer = 1;
>    {
>        let $outer = 2;  // E_COMPILE_ERROR to declare in a different 
> (shadowed) scope, can only reassign
>        $outer = 3;   // this is allowed
>     }
> }

> P.S. If you really need block scope within a long function or method you can 
> already create a closure and call it in the same expression:

I'm aware of this and have used it (e.g. to avoid modifying the global scope in 
large projects),
but avoid it in functions due to the awkward syntax and the performance 
overhead of function calls.
I'd generally just use a different variable name.

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

Reply via email to