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