Welcome to my series on every PHP keyword and its usage. Today’s item: instanceof.

The instanceof operator allows you to check if an object is an instance of a particular class (or a class that extends a particular class) or implements a particular interface.

Most of the time you’ll directly check if an object implements a specific class, but you can also check it against a class name stored inside a variable.

Notes:

  • You cannot use instanceof with a string literal, including the special ::class construct.
  • You cannot check if an object uses a specific trait using instanceof.

Syntax

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
$date = new DateTime();

// Check if true
if($date instanceof DateTime)
{
	echo "Date is an instance of DateTime";
}

// DateTime implements DateTimeInterface
if($date instanceof DateTimeInterface)
{
	echo "Date is an instance of DateTimeInterface";
}

// Check if false
if(!$date instanceof DateInterval)
{
	echo "Date is not an instance of DateInterval";
}

// You can check if an object is an instance of a class name stored inside a
// variable
$className = DateTimeZone::class;

if($date instanceof $className)
{
	echo "Date is, inexplicably, an instance of " . $className;
}