如何检查对象是否是特定 class 的实例?

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

有没有办法检查一个对象是否是 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);
        }
    }
}

这是我的函数,$role->xpath 只有在提供的对象是 SimpleXMLElement 时才有可能。有人吗?

您可以使用 instanceof 检查对象是否是 class 的实例,例如

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

以下方法和运算符可用于确定特定变量是否是指定 class 的对象:

  • $var instanceof TestClass: 运算符“instanceof”returns true 如果 变量 $var 是指定 class 的对象(这里是: “测试类”)。
  • get_class($var): Returns 来自$var的class的名字,可以 与所需的 class 名称进行比较。
  • is_object($var): 检查变量$var是否为对象。

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

中阅读更多内容