Snickbrack
Snickbrack

Reputation: 976

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

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?

Upvotes: 57

Views: 68703

Answers (2)

thomas
thomas

Reputation: 915

The following methods and operators are useful to determine whether a particular variable is an object of a specified class:

  • $var instanceof TestClass: The operator “instanceof” returns true if the variable $var is an object of the specified class (here is: “TestClass”).
  • get_class($var): Returns the name of the class from $var, which can be compared with the desired class name.
  • is_object($var): Checks whether the variable $var is an object.

Read more in How to check if an object is an instance of a specific class in PHP?

Upvotes: 16

Rizier123
Rizier123

Reputation: 59701

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

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

Upvotes: 116

Related Questions