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.
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 .
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.
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.
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).
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