How to check if a variable is of a certian class (considering PHP 5.3 namespace too)
How can I validate if an object is of a certian class? I currently use
get_class($obj) == 'User';
But it may look like 开发者_运维百科\KM\User
when I am elsewhere? I think this way maybe abit prone to developer error. Is there something like:
compare_class($obj1, User);
// or maybe
classof($obj) == User;
Use the instanceof operator:
if($foo instanceof User) {
...
}
Just
if ($obj instanceof User) {
// $obj is of User or any descendant
}
should do it. This is affected by the 5.3 namespace handling, which means: If you are in my\namespace
, it assume User
to be \my\namespace\User
. Or if you have something like use another\namespace\User
it will be treated as exactly that class specified by the use
-statement.
精彩评论