Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple instanceof checks

Tags:

php

instanceof

Is there a shorter way of checking if a object is part of a certain set of classes?

Using instanceof makes the if statement too long:

if($obj instanceof \Class1 || $obj instanceof \Class2 || $obj instanceof \Class3)

And this doesn't work:

instance of \Class1 || \Class2 || \Class3

It assumes that Class2 is constant.

like image 596
Alex Avatar asked May 29 '12 15:05

Alex


People also ask

What is Instanceof check Java?

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

Does Instanceof check for subclasses?

As the name suggests, instanceof in Java is used to check if the specified object is an instance of a class, subclass, or interface. It is also referred to as the comparison operator because of its feature of comparing the type with the instance.

Does Instanceof check for NULL?

Using the instanceof Operator When an Object Is null If we use the instanceof operator on any object that's null, it returns false. We also don't need a null check when using an instanceof operator.


1 Answers

makes the IF statement too long

[...]

Is there a shorter way

Sure.

Simply create a function:

function isOfValidClass($obj)
{
    $classNames = array('Class1', 'Class2');
    foreach ($classNames as $className) {
        if (is_a($obj, $className)) {
        return true;
    }

    return false;
}

Then you can use that in your code and not have to worry about your if statement "taking up too much room" (not that you should ever consider that an issue; statements should be as long as they need to).

like image 200
webbiedave Avatar answered Sep 21 '22 15:09

webbiedave