How to make a negation condition with instanceof, without affecting the order of precedence?

3

I hope the question does not seem strange, but I can clearly explain what I mean. I know that for checks, sometimes you have to be careful about the question of operator precedence or the conditions added in an if.

My question is: Which is the best way to know that an object is not an instance of a class through instanceof

Generally, we use it to find out if it is an instance. So:

if ($object instanceof WallaceMaxters\Timer\Time) {

}

However, what if I want to know that it is not an instance?

I've thought of using it this way:

!$object instanceof Timer

What I want to know is this: When I put ! deny sign in $object , I run some risk of being wrongly evaluated in my condition; that is, evaluate a boolean instead of an object.

Changing in kids. This ...

$object = new NotTimer;

!$object instanceof Timer

It would be evaluated like this ...

NotTimer(object) instanceof Timer

Or this?

false instanceof Timer

Note

I've seen frameworks that do this:

!($object instanceof Timer)

But is this really necessary, or is there really a possible problem in generating a deny signal condition before instanceof ?

    
asked by anonymous 18.10.2015 / 00:26

1 answer

3

If you look at the PHP operator precedence table , you'll see that instanceof takes precedence greater than ! . This means that, in an expression that includes both, instanceof is applied before. So the two variants are equivalent:

// Neste caso, a versão sem parênteses:
!$object instanceof Foo

// significa exatamente o mesmo que:
!($object instanceof Foo)

The option to use parentheses or not is who writes the code. Opting for parentheses can be a way to make your intention clear if doubt about precedence arises in whoever is reading.

    
19.10.2015 / 18:38