Re: Local constants
| From: | John Bafford | Date: | Wed, 04 Sep 2024 21:11:25 +0000 |
| Subject: | Re: Local constants | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-125430@lists.php.net to get a copy of this message | ||
> On Sep 4, 2024, at 16:45, Rob Landers <rob@bottled.codes> wrote:
>
> I think, conceptually, this makes sense, but maybe I'm the only one who writes
>
> $arr = doSomething();
> $arr = array_map(fn($x) => $x->prop, $arr);
> $arr = array_filter($arr, $filterFunc);
>
> instead of
>
> $arr = array_filter(array_map(fn($x) => $x->prop, doSomething()), $filterFunc);
IMO, that's a failing of PHP not supporting object syntax (and reasonable api) for non-object
values. In other languages, I can write code such as:
let arr = doSomething()
.map { $0.prop }
.filter(filterFunc)
Which is more readable than both PHP versions.
> And I feel like having constant variables would result in more of the latter, which I feel is
> more unreadable. Though I do note that my opinion of what is readable might be different from other
> people's.
>
> That being said, I would much rather see block-scoped variables than local variables via let or
> var or something:
>
> var $aNumber = 12;
>
> foreach($arr as var $item) {
> echo $item; // item exists here
> }
>
> echo $item; // item doesn't exist here
>
> PHP is simply too verbose to really benefit from local constants, but would benefit from
> block-scope far more. For example, with local constants, you couldn't write that foreach
> because that variable exists in the scope of the function and can only be defined once.
>
> — Rob
I'd suggest that the foreach could be written with either of let/var to both locally scope
$item, which would explicitly disallow/allow $item to be changed while in the loop.
Another benefit of local constants is preventing accidentally reusing a prior variable. For example,
if I set a temporary variable to something, and then later in the function, reuse that same name for
a new temporary but don't set the value on all flow paths, then the value from earlier in the
function leaks through, whereas either using a constant, or a second explicit variable definition
would have exposed and/or prevented the issue.
-John