PHP: is_exception()

I have an object in PHP that I need to check if it is an exception and act appropriately. Surprisingly PHP does not have an is_exception() function built in so I had to write my own:

function is_exception($obj,$strict = false) {
    if (!is_object($obj)) {
        return false;
    }

    // It's some type of exception
    if ($obj instanceof Exception) {
        if (!$strict) {
            return true;
        // It's a raw exception
        } elseif (get_class($obj) === "Exception") {
            return true;
        }
    }

    return false;
}

If you pass true as the second parameter it will only return true if it's a raw exception and not an inherited exception.

Leave A Reply
All content licensed under the Creative Commons License