Put constants and values on the left

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: php-best-practices/avoid-yoda-conditions

Language: PHP

Severity: Notice

Category: Best Practices

Description

In PHP, it is a recommended practice to put constants and literals on the right side of comparison operators such as == or ===. This rule is important because it helps prevent potential bugs caused by accidental assignment instead of comparison. Accidentally writing = instead of == is a common mistake, but if the constant is on the left side, PHP will throw an error, making the problem apparent.

Non-compliant code may still function as expected, but it can lead to confusion and hard-to-spot bugs, especially in large codebases or among teams of developers. It is also not considered a best practice in terms of code readability and maintainability.

To avoid this, always place your constants or literals on the right side of your comparison operators. This not only aligns with common practice, but also it allows PHP’s own error handling to assist in catching any accidental assignment errors. This can increase the robustness of your code and decrease debugging time.

Non-Compliant Code Examples

<?php
if (51 == something) {

}

if ("myValue" == something) {

}

if (0.0 == value && 0 == plop) {

}

Compliant Code Examples

<?php
if (something == 51) {

}

if (something == "myValue") {

}

if (value == 0.0 && plop == 0) {

}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: may/unit-testing