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?
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) .
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.
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 .
Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With