PHP 7.2.0 Release Candidate 2 Released

Type Operators

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:

Example #1 Using instanceof with classes

<?php
class MyClass
{
}

class 
NotMyClass
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>

The above example will output:

bool(true)
bool(false)

instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:

Example #2 Using instanceof with inherited classes

<?php
class ParentClass
{
}

class 
MyClass extends ParentClass
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>

The above example will output:

bool(true)
bool(true)

To check if an object is not an instanceof a class, the logical not operator can be used.

Example #3 Using instanceof to check if object is not an instanceof a class

<?php
class MyClass
{
}

$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>

The above example will output:

bool(true)

Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface:

Example #4 Using instanceof for class

<?php
interface MyInterface
{
}

class 
MyClass implements MyInterface
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>

The above example will output:

bool(true)
bool(true)

Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable:

Example #5 Using instanceof with other variables

<?php
interface MyInterface
{
}

class 
MyClass implements MyInterface
{
}

$a = new MyClass;
$b = new MyClass;
$c 'MyClass';
$d 'NotMyClass';

var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
?>

The above example will output:

bool(true)
bool(true)
bool(false)

instanceof does not throw any error if the variable being tested is not an object, it simply returns FALSE. Constants, however, are not allowed.

Example #6 Using instanceof to test other variables

<?php
$a 
1;
$b NULL;
$c imagecreate(55);
var_dump($a instanceof stdClass); // $a is an integer
var_dump($b instanceof stdClass); // $b is NULL
var_dump($c instanceof stdClass); // $c is a resource
var_dump(FALSE instanceof stdClass);
?>

The above example will output:

bool(false)
bool(false)
bool(false)
PHP Fatal error:  instanceof expects an object instance, constant given

There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This can be worked around by using a dynamic class reference, or a string variable containing the class name:

Example #7 Avoiding classname lookups and fatal errors with instanceof in PHP 5.0

<?php
$d 
'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>

The above example will output:

bool(false)

The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof. Note that as of PHP 5.3.0, is_a() is no longer deprecated.

See also get_class() and is_a().

add a note add a note

User Contributed Notes 19 notes

up
28
dava
3 years ago
You are also able to compare 2 objects using instanceOf. In that case, instanceOf will compare the types of both objects. That is sometimes very useful:

<?php

class A { }
class
B { }

$a = new A;
$b = new B;
$a2 = new A;

echo
$a instanceOf $a; // true
echo $a instanceOf $b; // false
echo $a instanceOf $a2; // true

?>
up
25
knarlin at yahoo dot com dot au
4 years ago
Checking an object is not an instance of a class, example #3 uses extraneous parentheses.

<?php
var_dump
(!($a instanceof stdClass));
?>

Because instanceof has higher operator precedence than ! you can just do

<?php
var_dump
( ! $a instanceof stdClass );
?>
up
15
jphaas at gmail dot com
10 years ago
Posting this so the word typeof appears on this page, so that this page will show up when you google 'php typeof'.  ...yeah, former Java user.
up
18
Sudarshan Wadkar
5 years ago
I don't see any mention of "namespaces" on this page so I thought I would chime in. The instanceof operator takes FQCN as second operator when you pass it as string and not a simple class name. It will not resolve it even if you have a `use MyNamespace\Bar;` at the top level. Here is what I am trying to say:

## testinclude.php ##
<?php
namespace Bar1;
{
class
Foo1{ }
}
namespace
Bar2;
{
class
Foo2{ }
}
?>
## test.php ##
<?php
include('testinclude.php');
use
Bar1\Foo1 as Foo;
$foo1 = new Foo(); $className = 'Bar1\Foo1';
var_dump($foo1 instanceof Bar1\Foo1);
var_dump($foo1 instanceof $className);
$className = 'Foo';
var_dump($foo1 instanceof $className);
use
Bar2\Foo2;
$foo2 = new Foo2(); $className = 'Bar2\Foo2';
var_dump($foo2 instanceof Bar2\Foo2);
var_dump($foo2 instanceof $className);
$className = 'Foo2';
var_dump($foo2 instanceof $className);
?>
## stdout ##
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
up
13
jtaal at eljakim dot nl
8 years ago
You can use "self" to reference to the current class:

<?php
class myclass {
    function
mymethod($otherObject) {
        if (
$otherObject instanceof self) {
           
$otherObject->mymethod(null);
        }
        return
'works!';
    }
}

$a = new myclass();
print
$a->mymethod($a);
?>
up
3
soletan at toxa dot de
10 years ago
Please note: != is a separate operator with separate semantics. Thinking about language grammar it's kind of ridicilous to negate an operator. Of course, it's possible to negate the result of a function (like is_a()), since it isn't negating the function itself or its semantics.

instanceof is a binary operator, and so used in binary terms like this

terma instanceof termb

while ! (negation) is a unary operator and so may be applied to a single term like this

!term

And a term never consists of an operator, only! There is no such construct in any language (please correct me!). However, instanceof doesn't finally support nested terms in every operand position ("terma" or "termb" above) as negation does:

!!!!!!!!!!!!!!term == term

So back again, did you ever write

a !!!!!!!!!!!!= b

to test equivalence?
up
6
fbableus
6 years ago
If you want to test if a classname is an instance of a class, the instanceof operator won't work.

<?php
$classname
= 'MyClass';
if(
$classname instanceof MyParentClass) echo 'Child of it';
else echo
'Not child of it';
?>

Will always output
Not child of it

You must use a ReflectionClass :
<?php
$classname
= 'MyClass';
$myReflection = new ReflectionClass($classname);
if(
$myReflection->isSubclassOf('MyParentClass')) echo  'Child of it';
else echo
'Not child of it';
?>

Will output the good result.
If you're testing an interface, use implementsInterface() instead of isSublassOf().
up
3
CH
3 years ago
You can use instanceof also for interfaces.
up
2
kevin dot benton at beatport dot com
9 years ago
Example #5 could also be extended to include...

var_dump($a instanceof MyInterface);

The new result would be

bool(true)

So - instanceof is smart enough to know that a class that implements an interface is an instance of the interface, not just the class.  I didn't see that point made clearly enough in the explanation at the top.
up
2
julien plee using g mail dot com
10 years ago
Response to vinyanov at poczta dot onet dot pl:

You mentionned "the instanceof operator will not accept a string as its first operand". However, this behavior is absolutely right and therefore, you're misleading the meaning of an instance.

<?php 'ClassA' instanceof 'ClassB'; ?> means "the class named ClassA is an instance of the class named ClassB". This is a nonsense sentence because when you instanciate a class, you ALWAYS obtain an object. Consequently, you only can ask if an object is an instance of a class.

I believe asking if "a ClassA belongs to a ClassB" (or "a ClassA is a class of (type) ClassB") or even "a ClassA is (also) a ClassB" is more appropriate. But the first is not implemented and the second only works with objects, just like the instanceof operator.

Plus, I just have tested your code and it does absolutely NOT do the same as instanceof (extended to classes)! I can't advise anyone to reuse it. The use of <?php is_instance_of ($instanceOfA, 'ClassB'); ?> raises a warning "include_once(Object id #1.php) …" when using __autoload (trying to look for $instanceOfA as if it was a class name).

Finally, here is a fast (to me) sample function code to verify if an object or class:

<?php
function kind_of (&$object_or_class, $class)
{
    return
is_object ($object_or_class) ?
       
$object_or_class instanceof $class
       
: (is_subclass_of ($object_or_class $class)
           ||
strtolower ($object_or_class) == strtolower ($class));
}
?>
up
1
archanglmr at yahoo dot com
12 years ago
Negated instanceof doesn't seem to be documented. When I read instanceof I think of it as a compairson operator (which I suppose it's not).

<?php
class A {}
class
X {}

//parse error from !
if (new X !instanceof A) {
    throw new
Exception('X is not an A');
}
//proper way to negate instanceof ?
if (!(new X instanceof A)) {
    throw new
Exception('X is not an A');
}
?>
up
1
wbcarts at juno dot com
5 years ago
SIMPLE, CLEAN, CLEAR use of the instanceof OPERATOR

First, define a couple of simple PHP Objects to work on -- I'll introduce Circle and Point. Here's the class definitions for both:

<?php

class Circle
{
  protected
$radius = 1.0;

 
/*
   * This function is the reason we are going to use the
   * instanceof operator below.
   */
 
public function setRadius($r)
  {
   
$this->radius = $r;
  }

  public function
__toString()
  {
    return
'Circle [radius=' . $this->radius . ']';
  }
}

class
Point
{
  protected
$x = 0;
  protected
$y = 0;

 
/*
   * This function is the reason we are going to use the
   * instanceof operator below.
   */
 
public function setLocation($x, $y)
  {
   
$this->x = $x;
   
$this->y = $y;
  }

  public function
__toString()
  {
    return
'Point [x=' . $this->x . ', y=' . $this->y . ']';
  }
}

?>

Now instantiate a few instances of these types. Note, I will put them in an array (collection) so we can iterate through them quickly.

<?php

$myCollection
= array(123, 'abc', 'Hello World!',
  new
Circle(), new Circle(), new Circle(),
  new
Point(), new Point(), new Point());

$i = 0;
foreach(
$myCollection AS $item)
{
 
/*
   * The setRadius() function is written in the Circle class
   * definition above, so make sure $item is an instance of
   * type Circle BEFORE calling it AND to avoid PHP PMS!
   */
 
if($item instanceof Circle)
  {
   
$item->setRadius($i);
  }

 
/*
   * The setLocation() function is written in the Point class
   * definition above, so make sure $item is an instance of
   * type Point BEFORE calling it AND to stay out of the ER!
   */
 
if($item instanceof Point)
  {
   
$item->setLocation($i, $i);
  }

  echo
'$myCollection[' . $i++ . '] = ' . $item . '<br>';
}

?>

$myCollection[0] = 123
$myCollection[1] = abc
$myCollection[2] = Hello World!
$myCollection[3] = Circle [radius=3]
$myCollection[4] = Circle [radius=4]
$myCollection[5] = Circle [radius=5]
$myCollection[6] = Point [x=6, y=6]
$myCollection[7] = Point [x=7, y=7]
$myCollection[8] = Point [x=8, y=8]
up
1
ejohnson82 at gmail dot com
9 years ago
The PHP parser generates a parse error on either of the two lines that are commented out here. 
Apparently the 'instanceof' construct will take a string variable in the second spot, but it will NOT take a string... lame

class Bar {}
$b = new Bar;
$b_class = "Bar";
var_export($b instanceof Bar); // this is ok
var_export($b instanceof $b_class); // this is ok
//var_export($f instanceof "Bar"); // this is syntactically illegal
//var_export($f instanceof 'Bar'); // this is syntactically illegal
up
0
wadih at creationmw dot com
1 month ago
Doing $a instanceof stdClass from inside a namespace will not work on its own.

You will have to do:

<?php
if ($a instanceof \stdClass)
?>
up
0
info at pkrules dot in
3 years ago
use this to check instance of or you can add the else part inside the if making it nested if for dual varification.:-
<?php
class MyClass{}
class
Test extends MyClass{
public function
checkObjectArray(array $array,$classname,$strict=false){
if(!
$strict){
foreach(
$array as $element){
if(!(
$element instanceOf $classname)){//we can use typehint objects
INSIDE an array
echo
"false";
echo
"<br />";
break;
}
else{
print
"<br />true (if)";
}
}
}
else{
foreach(
$array as $element){
if(
get_class($element)!=$classname){// or we can use this function to
check the classes inside this array
echo
"false (else)";
}
}
}
echo
"<br />true";
}
}
$ob=new Test;

$a=new MyClass();
$array=array($a);
$ob->checkObjectArray($array,'MyClass');
?>
up
0
jeanyves dot terrien at orange-ftgroup dot com
10 years ago
Cross version function even if you are working in php4
(instanceof is an undefined operator for php4)

   function isMemberOf($classename) {
      $ver = floor(phpversion());
      if($ver       an clasdO">get_2n>
   function isMemberOf($classename) {
  &nbs1ics="default">MyClass
(me$on ("tererm == term

So back/
p; &nbs1ics="d"genanchor" href="#76582"> ¶Pnbs/>ecs p; &nbs1ics="d"genanchor" href="#765ed in/a>end ef="/manual/vote-note.php?id=73853&page=language.operators.4831&vote=up" title="Vote up!" class="us4831&amotes-voted">down
down
0
jeany4831&at terrien at orange-ftgroup dot com
> C42ated instanceof doesn't seem to be documented. When I read instanc4831&among it nested if for dual varification.:-
{}
class
Test ,);
'$myCollection[' $element  class="keyword">){
foreacwordMyClass'
);
$a);
$element &nbbr />  class="keyword">){
forealIIO_INSTANCE>   
$item$element &nbbsp;&nbbsp;&nbbsp;&nbbsp;&nbpan>) ?
pan>s="default">MyClass
 &nbbsp;&nbbsp;&nbbsp;&nbbsp;&nb}n clasbr /> &nbbsp;&nbbsp;&nb &nbbsp;&nbbsp;&nbbsp;&nbbsp;&nbpan>) ?
ch(
$aan clasbr /> &nbbsp;&nbbsp;&nbbsp;&nbbsp;&nb}n clasbr /> &nbbsp;&nbbsp;&nb}n clasbr /> &nb){
foreacwordMyClass'
);
$a);
 &nbbsp;&nbbsp;&nbpan>) ?
&nbdefault">checkObjectArray);
'$myCollection[' $element &nbbsp;&nbbsp;&nb}n clasbr /> &nb &nbbsp;&nbbsp;&nbpan>) ?
ch(
$aan clasbr /> &nbbsp;&nbbsp;&nb}n clasbr /> &nbyCollection[2] = Hello World!
$myCollection down
down
0 jeany99384a 0 3dot com<-ong>
<?php<="string">"fals /> echo ;
}ass="e
{
  protected
$arralass="keyword">,$classname,$strictINSIDE an $myCollection AS $ar=emberOf($classename) classas $element  n class class="keyword">)
get_class
($element  ($classename) class>)){//we can use typehintdefault">is_subclass_of INSIDE an ) ?
ch(
$aan clasbr /> &nbbsp;&nbbsp;&nbbsp;&nbbsp;&nb}n clasbr /> &nbbsp;&nbbsp;&nb}n clasbr /> &nb}n clasbr /> &nb  n class class="keyword">)
get_class
($element  ($classename) clas"keyword">)!=$classname){// or we can use this f ! class="default">__toStringINSIDE an   ($classename) bsp;&nbbsp;&nbpan>) ?
ch(
$aan clasbr /> &nbbsp;&nbbsp;&nbbsp;&nbbsp;&nb}n clasbr /> &nbbsp;&nbbsp;&nb}n clasbr /> &nb}n clasbr /> &nbpan>) ?
pan>s="default">MyClass
$myCollection down
down 0 jeany9892pe><-5ng>" href="#73853"> ¶
4:13 this to c7eof doesn't seem to be documented. When I read instanc9892pe&ooperator won't work.

$bdR!tn the Collection[2egnstanceof is clas>
down add/div> stri<>><>class?id=73ef=