- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- Administrator's Guide
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: php-best-practices/unset-loop-references
Language: PHP
Severity: Warning
Category: Error Prone
This rule requires that all references created during loops, such as foreach
, should be unset after the loop has completed. This is important because PHP handles variable scope differently than some other programming languages. In PHP, a reference set inside a foreach
loop will continue to exist after the loop has finished, potentially leading to unexpected behavior.
If a reference is not unset after a loop, it can accidentally be used later in the code, causing bugs that are difficult to trace. In the non-compliant code sample, $value
is a reference to each element of $arr
in the loop. After the loop, $value
is still a reference to the last element of $arr
. If $value
is modified, the last element of $arr
is also modified, which is likely not the intended behavior.
To avoid this, always explicitly unset references after the loop with unset()
. This good practice ensures that the reference does not persist beyond its intended scope, preventing potential bugs and making your code more robust and easier to understand. Following this rule will help you write cleaner, more predictable code and reduce the likelihood of encountering difficult-to-diagnose bugs.
<?php
foreach ($arr as &$value) {
$value += 10;
}
$value = 'x';
<?php
foreach ($arr as &$value) {
$value += 10;
}
unset($value);
$value = 'x';
|
|
For more information, please read the Code Analysis documentation
Identify code vulnerabilities directly in yourVS Code editor
Identify code vulnerabilities directly inJetBrains products