Javascript debugger
Website design
↑
instanceof
is used to determine whether a PHP variable
is an instantiated object of a certain
class:
<?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:
<?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)
Lastly, instanceof
can also be used to determine whether
a variable is an instantiated object of a class that implements an
interface:
<?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:
<?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)
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:
<?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
.
See also get_class() and is_a().