On 2/23/26 15:58, Kamil Tekiela wrote:
On Mon, 23 Feb 2026 at 21:29, Joshua Rüsweg <[email protected]> wrote:
Hi internals,
I'd like to propose a new language feature for PHP: Readonly Variables.
PHP currently has no way to declare a variable as immutable within a local or
functional scope. This RFC proposes the readonly modifier for variables, which
prevents reassignment after the initial declaration and results in an error on
any attempt to do so.
Key behaviors:
- Reassignment and compound assignment operators are forbidden
- Pass-by-reference is forbidden
- unset() removes the readonly flag, allowing re-declaration
- Readonly variables inside loops are permitted but limited to a single
declaration
- Scoping follows regular variable rules (function, method, closure boundaries)
The RFC is available at:
https://wiki.php.net/rfc/readonly-variables
I'm looking forward to your feedback and discussion.
Cheers,
Joshua Rüsweg
Hi Joshua,
This is a very interesting proposal, but I feel like you haven't
explained all your choices. I have some questions:
1. Why the use of readonly keyword? Why not const or some new keyword,
e.g. locked.
2. Why does unset not remove the variable completely? If you want a
feature to only unlock the variable then it probably needs a new
keyword, e.g. unlock
3. What exactly does this mean: "Readonly variables inside loops are
permitted but limited to a single declaration"? What does a single
declaration look like?
4. How will this impact optimizer and JIT?
5. You said that readonly variables cannot be used with the global
keyword. But what about readonly variables in global scope? Will they
still behave like a typical global variable?
6. What exactly counts as a variable declaration? When is it a valid
syntax to use this keyword? I don't think PHP had the concept of
variable declaration until now.
7. What about compound variables such as arrays and objects?
I would prefer starting with readonly parameters as I feel that would
bring the most value.
I think it would also be worthwhile to investigate a simpler syntax
for define().
Regards,
Kamil
In addition to Kamil's questions, I'm concerned about the "taking a
reference is forbidden" and "pass-by-reference is forbidden"
requirements. Objects are references, whether or not using the `&` operator.
According to this RFC, both of these would be forbidden:
readonly $a = new Foo();
$b = $a;
and:
function modify(Foo $value): void {}
readonly $a = new Foo();
modify($a);
I said "according to this RFC," but the RFC doesn't mention object
behavior with readonly at all, which I think might be an oversight. The
only place it hints at allowing objects is in the examples with `new PDO()`.
Is the idea to allow objects (and arrays) similar to how JavaScript
handles these with `const`? That is, the objects and arrays themselves
are mutable, but the variable name cannot be reassigned to a new object
or array?
Cheers,
Ben