[php-src] Issue #13231: foreach(readonly)
| From: | SVGAnimate | Date: | Tue, 23 Jan 2024 17:50:24 +0000 |
| Subject: | [php-src] Issue #13231: foreach(readonly) | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-246325@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/13231
Author: SVGAnimate
### Description
This code should be able to stop before crashing.
```PHP
<?php
$fib = [0, 1];
foreach($fib as $n=>$fib_n) {
$fib[] = $fib[$n] + $fib[$n+1];// ! \ $fib is readonly / ! \\
}
print_r($fib);
```
But in this way, it is not intuitive : security is minimal. I would have preferred to be notified by
a warning
```
Array
(
[0] => 0
[1] => 1
[2] => 1
[3] => 2
)
```
<hr />
As in many other languages, variables declared in a foreach are not writable. In PHP we can modify
this behavior thanks to the reference operator `
&`
However, there is a difference between being able to modify the content and the container.
Also, I would like to know how you perceive this type of writing:
```PHP
<?php
foreach(&$fib = [0, 1] as $value) {
$fib[] = $fib[$n] + $fib[$n+1];
}
print_r($fib);// [0,1, 1, 2, 3, 5, 8, ...]
```
Or perhaps in the other way, more tedious, less coherent, more dangerous
```PHP
<?php
$init = [0, 1];
$fib = &$init;
foreach(readonly $fib as $value) {
$fib[] = $fib[$n] + $fib[$n+1];
}
print_r($fib);// [0,1, 1, 2] Stoped at count($__fib);
$fib=[0, 1];
foreach([0, 1] as $value) {
$fib[] = $fib[$n] + $fib[$n+1];
}
print_r($fib);// [0,1, 1, 2] Stoped at count([0, 1]);
```