Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

simplexml

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?

like image 273
Snickbrack Avatar asked May 19 '15 16:05

Snickbrack


People also ask

Is an object is an instance of its class?

an object is an element (or instance) of a class; objects have the behaviors of their class. The object is the actual component of programs, while the class specifies how instances are created and how they behave.

How do I check if an object is an instance of a given class or of a subclass of it?

The isinstance() method checks whether an object is an instance of a class whereas issubclass() method asks whether one class is a subclass of another class (or other classes).

What is an object an object is an instance of a class?

A class can create objects of itself with different characteristics and common behaviour. So, we can say that an Object represents a specific state of the class. For these reasons, an Object is called an Instance of a Class.


2 Answers

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

if($role instanceof SimpleXMLElement) {     //do stuff } 
like image 177
Rizier123 Avatar answered Sep 20 '22 03:09

Rizier123


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?

like image 33
thomas Avatar answered Sep 22 '22 03:09

thomas