instanceof, Precedence and Associativity

7.instanceof, Precedence and Associativity

M

In this chapter

We'll learn how PHP decides which part of an expression to work out first — operator precedence, associativity and brackets — with the instanceof operator for objects, so you can read any line like PHP does and explain why && beat ||, why minus 2 to the power 2 is -4 and why 10 - 4 - 3 is 3.

13–15 min

The Problem in Real Life

Mia has fixed four bugs this week by adding brackets. She wants to understand the rule behind all of them. Marcus writes three lines on the board: $isFree && $isMember || $paysOnline, -2 ** 2, and 10 - 4 - 3.

"In each line," he says, "PHP has to decide what to work out first. It doesn't guess — it follows a ranking of every operator, plus one rule for ties. Once you know them, you'll know when brackets are needed. And you'll add them anyway."

M

How does PHP decide what to work out first when a line has five operators in it?

Mia

Left to Right vs. Strongest First

Many operators, one line

A long expression has many possible orders — but only one result.

Ties between equals

10 - 4 - 3 and 2 3 2 group in opposite directions.

Checking an object's class

Objects need their own kind of comparison: "is this a Booking?"

instanceof, Precedence and Associativity

Three rules decide the order: when an expression has several operators, PHP groups them using three rules, in this order:

  • Brackets first: anything in ( ) is worked out before everything around it.
  • Precedence: operators with a higher precedence grab their operands first — like × before + in school maths.
  • Associativity: when operators of the same precedence meet, it decides whether PHP groups from the left or from the right.

Precedence: every operator has a rank. Higher-ranked operators are grouped first. The table below lists the ones you know, from strongest to weakest. You don't need to memorise all of it — a few facts cover almost everything: maths before comparisons ($a + 1 > $b compares the sum), comparisons before &&, && before ||, ?? and the ternary near the bottom, and assignment almost at the very bottom (so $total = $a + $b adds first, then stores). The words and, or and xor sit even below assignment — the trap from chapter 3.

Table — Precedence, strongest first (the operators you know)
OperatorsWhat they areGroups from
**PowerRight
++ -- ~ (int) (string) … and unary -Increment, casts, negation—
instanceofClass checkLeft
!Logical not—
* / %Multiply, divide, remainderLeft
+ -Add, subtractLeft
<< >>Bit shiftsLeft
.Concatenation (below + and - since PHP 8)Left
< <= > >=Bigger / smallerCan't chain
== != === !== <> <=>Equality, spaceshipCan't chain
& then ^ then |BitwiseLeft
&&Logical andLeft
||Logical orLeft
??Null coalescingRight
? :TernaryCan't nest without brackets
= += -= .= ??= …AssignmentRight
and, then xor, then orWord versions of logicLeft

The new pipe operator |> (chapter 8) sits between . and the comparisons.

Explaining this week's bugs: with the table, each surprise has a reason. $isFree && $isMember || $paysOnline groups the && first, because it ranks above ||. In -2 ** 2, the power ** ranks above the minus sign, so it's -(2 ** 2), which is -4. And in "Total: " . $a + $b, PHP 8 gives + a higher rank than ., so the sum is worked out first (chapter 8 explains why that changed).

This week's bugs, explained by precedence
<?php
var_dump(2 + 3 * 4); // int(14): * before +
var_dump((2 + 3) * 4); // int(20): brackets first
var_dump(-2 ** 2); // int(-4): ** before the minus sign
var_dump(true || false && false); // bool(true): && before ||
var_dump(!true && false); // bool(false): ! before &&

Associativity: when operators of the same rank meet, PHP needs a tie-breaker. Most operators are left-associative: 10 - 4 - 3 is (10 - 4) - 3 = 3, and 100 / 10 / 5 is 2. A few are right-associative: 2 ** 3 ** 2 is 2 ** (3 ** 2) = 512, and assignment groups from the right, which is why $a = $b = 0 works. And some are non-associative — they can't be chained at all: 1 < 2 < 3 is a parse error (chapter 2), because "compare a bool with 3" makes no sense.

Associativity: left, right and not at all
<?php
var_dump(10 - 4 - 3); // int(3): (10 - 4) - 3, left to right
var_dump(100 / 10 / 5); // int(2): (100 / 10) / 5
var_dump(2 ** 3 ** 2); // int(512): 2 ** (3 ** 2), right to left
$a = $b = 0; // $a = ($b = 0), right to left
var_dump($a, $b); // int(0) int(0)
// var_dump(1 < 2 < 3); // Parse error: comparisons can't be chained

instanceof: $value instanceof ClassName is the comparison operator for objects. It gives true if $value is an object of that class, of a class that extends it, or of a class that implements that interface (Act 04, chapters 6 and 8). It ranks very high, so !$b instanceof Booking means !($b instanceof Booking) — but write the brackets so readers don't have to know that. For anything that isn't an object, instanceof is simply false.

instanceof
<?php
$slots = new ArrayObject(["9:00", "9:30"]);
var_dump($slots instanceof ArrayObject); // bool(true)
var_dump($slots instanceof Countable); // bool(true): an interface it implements
var_dump(!($slots instanceof Countable)); // bool(false): brackets make it obvious
var_dump("9:00" instanceof ArrayObject); // bool(false): not an object

Brackets are for people too: the professional rule is simple. If a reader has to think about precedence, add brackets — even where PHP would get it right. ($isFree && $isMember) || $paysOnline and $isFree && ($isMember || $paysOnline) can't be confused; the version without brackets can, and was. Brackets cost nothing at runtime. When a line still needs a lot of brackets, split it into named variables, as in chapter 3.

Key Takeaway

PHP groups an expression by brackets first, then by precedence (stronger operators first: before unary minus, maths before comparisons, && before ||, assignment near the bottom, and/or/xor below it), then by associativity for ties (most operators left, and assignment right, comparisons non-associative). instanceof checks an object's class. When precedence isn't obvious, add brackets or name the parts.

Why This Matters

Precedence is behind a surprising number of real bugs — the double booking at BookBay was one. Knowing the few rules that matter lets Mia read any line exactly as PHP does, and spot the lines where the grouping is ambiguous.

The habit that comes with it — brackets and named parts whenever a reader might hesitate — is what makes code reviews fast and conditions trustworthy.

Mia can now explain every bracket she added this week. Marcus has one last topic for the Act: PHP 8 changed how some expressions behave, and PHP 8.5 — the version BookBay runs — added a brand-new operator for chaining steps together. "You'll see it in new code," he says, "and it might change how you write some of yours." That's the next chapter.