Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check if an object is kind of a specific class, in PHP? [duplicate]

Tags:

php

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?

like image 218
openfrog Avatar asked Dec 27 '09 10:12

openfrog


People also ask

How do you check if an object is a certain class PHP?

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.

How do you check if an object is an instance of a particular type?

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.

How check object is empty or not in PHP?

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.


1 Answers

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.

like image 136
Pascal MARTIN Avatar answered Oct 11 '22 14:10

Pascal MARTIN