Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof negation

Tags:

php

instanceof

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?

like image 347
Mathew Avatar asked Jan 16 '13 16:01

Mathew


People also ask

How do you know if you're not Instanceof?

To check if an object is not an instance of a class, use the logical NOT (!) operator to negate the use of the instanceof operator - !( obj instanceof Class) .

What does Instanceof mean?

instanceof is a binary operator we use to test if an object is of a given type. The result of the operation is either true or false. It's also known as a type comparison operator because it compares the instance with the type. Before casting an unknown object, the instanceof check should always be used.

What does Instanceof do in java?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

What can I use instead of Instanceof?

Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".


1 Answers

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.

like image 190
Álvaro González Avatar answered Sep 21 '22 15:09

Álvaro González