Re: RFC idea: Block scoped variables with "let $x = expr"

From: Date: Sun, 15 Mar 2020 20:37:45 +0000
Subject: Re: RFC idea: Block scoped variables with "let $x = expr"
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-109040@lists.php.net to get a copy of this message
Tyson Andre wrote:
Hi internals, In PHP, variables are currently scoped to the function scope, and can't be scoped to a block scope. This makes it difficult to reason about how a variable will actually be used at a glance, especially in long functions, or top-level statement lists of a file. (or how the variable was originally intended to be used) The function scope lifetime of variables in PHP is similar to how JavaScript treated variables with var, before the introduction of the let statement in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let Would there be any interest in adding something similar to this in PHP?
I'd definitely like this, and this has also been proposed as a possible future direction in the "Variable declarations before usage" RFC: https://wiki.php.net/rfc/declare_vars For reasons of backwards compatibility and avoiding having to add new keywords, we may want to consider using "var", instead of "let". Starting with scoped variables could also evolve into requiring variables to be declared using the optional "declare(declare_vars=1)" directive from the above proposal. For me, perhaps the most interesting spin-off of adding optional variable declarations would be the possibility of using typed local variables (also suggested in the above proposal), maybe something like: declare(typed_vars=1); // In case we want opt-in var $message = "Test"; // No type declaration needed, type inferred as "string" ... $message = null; // Error $message is of type string $message = new SomeMessage(); // Error $message is of type string If we don't have an initialiser, we might specify the type explicitly (note: I'm here talking about what explicitly declaring variables may be used for in the future, I'm not proposing this now): var ?string $message; ... $message = null; // OK $message = "Test"; // OK $message = new Something(); // Error, $message is of type ?string Regards, Terje

« previous php.internals (#109040) next »