1.2.53. Assign And Lettered Logical Operator Precedence

The lettered logical operators and, or and xor have lower precedence than assignation. It collects less information than expected.

When that precedence is taken into account, this is valid and useful code. Yet, as it is rare and surprising to many developers, it is recommended to avoid it.

It is recommended to use the &&, ^ and || operators, instead of and, or and xor, to prevent confusion.

<?php

// The expected behavior is
// The following are equivalent
 $a =  $b  && $c;
 $a = ($b && $c);

// The unexpected behavior is
// The following are equivalent
 $a = $b  and $c;
($a = $b) and $c;

// Here, the result is collected. That result would not make use of the result of the throw expression
$a = doSomething() or throw new Exception('Error happened');

?>

See also Operator Precedence.

1.2.53.1. Suggestions

  • Use symbolic operators rather than letter ones

  • To be safe, add parenthesis to enforce priorities

1.2.53.2. Specs

Short name

Php/AssignAnd

Rulesets

All, Analyze, CE, CI-checks

Exakat since

0.12.4

PHP Version

All

Severity

Critical

Time To Fix

Quick (30 mins)

Precision

Very high

Features

precedence, operator, logical-operator

Examples

xataface

Available in

Entreprise Edition, Community Edition, Exakat Cloud