tags:

views:

78

answers:

4

Example: A method is supposed to return an instance of a SpecificClass. How can I check that return value if it is from that class?

+3  A: 
if ($object instanceof classname)
 ....

Manual: Classes and Objects in PHP5

Pekka
+12  A: 

You can use the instanceof operator, to check if an object is an instance of :

  • A class
  • Or a child class of that class
  • Or an instance of a class that implements an interface

Which means that it cannot be used to detect if your object is an instance of a specific class -- as it will say "yes" if your object is an instance of a child-class of that class.


For instance, this portion of code :

class ClassA {}
class ClassB extends ClassA {}

$a = new ClassB();
if ($a instanceof ClassA) {
    echo '$a is an instanceof ClassA<br />';
}
if ($a instanceof ClassB) {
    echo '$a is an instanceof ClassB<br />';
}

Will get you this output :

$a is an instanceof ClassA
$a is an instanceof ClassB

$a, in a way, is an instance of ClassA, as ClassB is a child-class of ClassA.

And, of course, $a is also an instance of ClassB -- see the line where it's instanciated.

Pascal MARTIN
+1 for the detailed explanation.
Pekka
@Pekka : Thanks ;-) I edited again, to provided an example ^^
Pascal MARTIN
as usual from Pascal, great quality answer. Thanks man.
openfrog
+3  A: 

You can't check the return value itself, but you can check the class that it's returned from using 'instanceof'. (On a similar basis, you may find 'get_class' useful.)

middaparka
+1  A: 

You can use the instanceof operator or the is_a function.

is_a is useful if you want to pass in a string with the name of the class (in a more dynamic codebase).

Emil Vikström