rspec/rules/S4824/php/rule.adoc

44 lines
1.3 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
When a reference is used in a ``++foreach++`` loop instead of using a simple variable, the reference remains assigned and keeps its "value" which is a reference, even after the ``++foreach++`` execution. Most of the time, this is not what the developer is expecting and the reference may be used wrongly in the rest of the code. For this reason, it is recommended to always ``++unset++`` a reference that is used in a ``++foreach++`` to avoid any unexpected side effects.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
$arr = array(1, 2, 3);
foreach ($arr as &$value) { // Noncompliant; $value is still alive after the loop and references the last item of the array: $arr[2]
$value = $value * 2;
}
$value = 'x';
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
$arr = array(1, 2, 3);
foreach ($arr as &$value) { // Compliant; there is no risk to use by mistake the content of $value pointing to $arr[2]
$value = $value * 2;
}
unset($value);
$value = 'x';
----
2021-04-28 16:49:39 +02:00
== See
* PHP Documentation: https://php.net/manual/en/control-structures.foreach.php[Foreach ]
* https://schlueters.de/blog/archives/141-references-and-foreach.html[References and Foreach]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]