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?
The instanceof keyword is used to check if an object belongs to a class. The comparison returns true if the object is an instance of the class, it returns false if it is not.
The JavaScript instanceof operator is used to check the type of an object at the run time. It returns a boolean value(true or false). If the returned value is true, then it indicates that the object is an instance of a particular class and if the returned value is false then it is not.
Using empty() won't work as usual when using it on an object, because the __isset() overloading method will be called instead, if declared. Therefore you can use count() (if the object is Countable). Or by using get_object_vars() , e.g.
You can use the instanceof
operator, to check if an object is an instance of :
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With