instanceof negation

PhpInstanceof

Php Problem Overview


Which is the correct format for negating instanceof?

if ( ! $a instanceof stdClass)

or

if ( ! ($a instanceof stdClass) ) 

I've convinced myself the latter is correct way, probably after reading a blog article several years ago, but after some command-line tests, they both seem equivalent. Are they?

Php Solutions


Solution 1 - Php

Let's read the docs:

> The following table lists the operators in order of precedence, with the highest-precedence ones at the top.[...]

Associativity      Operators       Additional Information
================== =============== ======================
non-associative    instanceof      types
right              !               logical

So instanceof has higher priority, thus both statements are equivalent. Parenthesis are probably used to make it obvious so you don't need to look it up in the documentation.

Solution 2 - Php

> Are they equivalent?

Yes, logically they are equivalent. The answer by Álvaro G. Vicario provides more detail why.

> Which is the correct format for negating instance of?

Of the two, there is an argument that the following is more readable. But there is no single way. That's the beauty and curse of PHP.

!($a instanceof stdClass)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMathewView Question on Stackoverflow
Solution 1 - PhpÁlvaro GonzálezView Answer on Stackoverflow
Solution 2 - PhpJason McCrearyView Answer on Stackoverflow