68

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?

Mathew
  • 8,203
  • 6
  • 37
  • 59
  • 1
    Yes, they are equivalent. – proskor Jan 16 '13 at 16:05
  • 2
    how about the more explicit `if ( false === $a instanceof Foo )`? Apart from that, there is no question here because the two expressions are easy enough to test on your own. – Gordon Jan 16 '13 at 16:06
  • 1
    @gor - nice [yoda condition](http://stackoverflow.com/a/2430307/558021) ;) – Lix Jan 16 '13 at 16:09

2 Answers2

107

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.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
18

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)
Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174