Grigory Ilizirov Grigory Ilizirov - 3 months ago 11
PHP Question

Is there a better way to check type of input parameter in php?

I want to check that the $duration is object of type DateInterval otherwise throw an exception. get_class function fails if $duration is not an object... and this code looks to long

if (is_object($duration)) {
if (get_class($duration) != "DateInterval") {
throw new \Exception('The provided duration is not DateInterval type.');
}
} else {
throw new \Exception('The provided duration is not DateInterval type.');
}


Is there a better way ?

Answer

I would use the instanceof method. See the example:

$obj = new A();

if ($obj instanceof A) {
    echo 'A';
}

https://secure.php.net/manual/en/internals2.opcodes.instanceof.php