如何检查变量是否属于certian类(也考虑PHP 5.3命名空间)


How to check if a variable is of a certian class (considering PHP 5.3 namespace too)

如何验证对象是否属于certian类?我目前使用

get_class($obj) == 'User';

但当我在其他地方时,它可能看起来像'KM'User?我认为这种方式可能有点容易引起开发人员的错误。有没有类似的东西:

compare_class($obj1, User);
// or maybe
classof($obj) == User;

使用instanceof运算符:

if($foo instanceof User) {
    ...
}

if ($obj instanceof User) {
  // $obj is of User or any descendant
}

应该这样做。这受到5.3命名空间处理的影响,这意味着:如果您在my'namespace中,它假设User'my'namespace'User。或者,如果您有类似use another'namespace'User的东西,它将被视为use-语句指定的类。