How can I check if a object is an instance of a specific class?

Snickbrack picture Snickbrack · May 19, 2015 · Viewed 11k times · Source

Is there a way to check if an object is an SimpleXMLELement?

private function output_roles($role) {
    foreach ($role as $current_role) {
        $role_ = $current_role->attributes();
        $role_type = (string) $role_->role;
        echo "<tr>";
        echo "<td><b>" . $role_type . "</b></td>";
        echo "</tr>";
        $roles = $role->xpath('//role[@role="Administrator"]//role[not(role)]');
        if (is_array($roles)) {
            $this->output_roles($roles);
        }
    }
}

This is my function and the $role->xpath is only possible if the provided object is a SimpleXMLElement. Anyone?

Answer

Rizier123 picture Rizier123 · May 19, 2015

You can check if an object is an instance of a class with instanceof, e.g.

if($role instanceof SimpleXMLElement) {
    //do stuff
}