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

Asked

Viewed 217 times

3

I hope the question does not sound strange, but I can clearly explain what I mean. I know that as far as checks are concerned, it is sometimes necessary to take care of the question of the operators' precedence or the conditions themselves added to an if.

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

We usually use it to find out if it’s an instance. Thus:

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

}

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

I’ve thought about using it that way:

!$object instanceof Timer

What I want to know is this: ! denial sign in $object, I run some risk of being misjudged my condition; that is, evaluate a boleano instead of an object.

Changing into kids. That...

$object = new NotTimer;

!$object instanceof Timer

Would be judged as that ...

NotTimer(object) instanceof Timer

Or this?

false instanceof Timer

Observing

I’ve seen frameworks that do that:

!($object instanceof Timer)

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

1 answer

3


If you look at PHP operator precedence table, will see that the instanceof takes precedence over !. This means that, in an expression that includes both, the instanceof is applied before. Therefore 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 the question about precedence arises in those reading.

  • Spoke and said friend! Very well explained!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.