Multiple Instance Checks

Is there a shorter way to check if an object is part of a specific set of classes?

Using instanceof makes the IF statement too long: if($obj instanceof \Class1 || $obj instanceof \Class2 || $obj instanceof \Class3....)

And this does not work: instance of \Class1 || \Class2 || \Class3 instance of \Class1 || \Class2 || \Class3

he assumes Class2 is permanent.

+6
source share
3 answers

In short: No

Longer answer: you can create workarounds that use get_parent_class() recursive to retrieve all the parent classes, and then use array_intersect() to find if one or more of your class names appears. However, it seems that the classes have something in common. Put this in the test interface against this.

+7
source

IF statement takes too long

[...]

Is there a shorter way

Of course.

Just 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 this in your code and not worry that your if statement "takes up too much space" (not that you ever thought the problem was, statements should be as they need).

+5
source

I think the shortest way is to output the Boolean expression to an external method and call it in the IF statement.

+1
source

Source: https://habr.com/ru/post/916927/


All Articles