Skip to content

Final or Readonly Local Variables #19416

@peterujah

Description

@peterujah

Description

It would be helpful if PHP supported a way to declare local variables as final or readonly, especially in dynamic include contexts. This could prevent accidental override of values in files brought in via include or require.

Example:

function load(string $file): void {
    final $config = ['foo' => 'bar'];
    include $file; // Would throw an error if $config is reassigned.
}

Function:

init_with_scope(function(){
    // Access extracted immutable variables
}, mixed: ['config' => $config]);

This could improve safety when including untrusted or dynamic files, and align with practices of immutability. I understand this could require significant changes to the language internals, but I think it's worth discussing whether something similar (even limited to function scope) could be feasible without hacking immutability.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions