On Sep 4, 2024, at 15:23, Rob Landers <rob@bottled.codes> wrote:
> 
> On Tue, Sep 3, 2024, at 05:20, HwapX wrote:
>> Hello internals!
>> 
>> I was wondering, has there been any discussion about supporting local 
>> constants (variables that cannot be reassigned, perhaps even function 
>> parameters)?
> 
> Out of curiosity, what value would this bring to PHP? In my experience, 
> modern php methods and functions tend to fit on a single screen, at most 
> being a few hundred lines for complex logic.
> 
> — Rob

This is about semantic clarity. If you define a variable as a constant, then, 
not only do you know for certain that it cannot change, you are also stating 
"it is my intent to not change this variable after setting it", and so if 
someone later tries to do so, they (should) have to answer the question, "*why* 
do I need to make this variable change?".

If it's useful to be able to annotate class members as being "readonly", it is 
likewise useful to do that on a local scope.

With sufficient compiler support, *typed* constant variable declarations might 
also allow for this:

        let SomeType $foo; //or readonly, or writeonce, or whatever
        
        if($something) {
                $foo = ...;
        } else if($somethingElse) {
                $foo = getSomeString(); //Error, type mismatch; possibly 
catchable at compile time, definitely with static analysis
        } else if($thirdCondition) {
                $foom = ...; //oops, typo
        } else {
                throw new Exception(...)
        }
        
        doSomething($foo); //Compiler error: $foo not initialized on all call 
paths.
}

You might also tighten scoping with such variables:

        foreach(...) {
                let $foo = //local working variable; possibly even shadowing a 
variable in the parent scope
        }

        //$foo is undefined; you can't access the last-set value from the loop 
outside of the loop

Static analysis can catch all these errors, but it'd be nicer to be able to do 
it without requiring docblocks. The language providing tools for being more 
explicit about intent in code is never bad.

-John

Reply via email to