50

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?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Snickbrack
  • 1,253
  • 4
  • 21
  • 56
  • 1
    possible duplicate of [How to Check for a Specific Type of Object in PHP](http://stackoverflow.com/questions/8091143/how-to-check-for-a-specific-type-of-object-in-php) – IMSoP May 19 '15 at 19:13

2 Answers2

94

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

if($role instanceof SimpleXMLElement) {
    //do stuff
}
Rizier123
  • 58,877
  • 16
  • 101
  • 156
13

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?

thomas
  • 785
  • 8
  • 7