Archive - Originally posted on "The Horse's Mouth" - 2009-05-07 19:21:45 - Graham Ellis
It should be very rare that you want to say "what type of object is this?" in PHP - or in any OO language; that's because with a correctly implemented class structure, you should have polymorphic effects that cause your code to perform the correct operation whatever object type you run in on. However - I said "rare" not "never"
The getclass method tells you what class a PHP object is a member of. Whereas the instanceof operator tells you if an object is a member of a class. Does that sound similar? Yes - but there is a subtle difference.
Let's say that $abc is a dog. That is what "getclass" will tell me. And instanceof will return me true if I ask whether $abc is a dog. but if a dog extends an animal, and implements insurable, then instanceof will also confirm that - yes - $abc IS animal and, yes, $abc is insurable.
In other words, getclass tells you a specific class name, whereas instanceof will confirm whether or not an object is a member of a whole series of base classes and interfaces, as well as the specific class in which it was constructed.