PHP Keywords: instanceof

12 March 2019 - 9:23am

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

<?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;
}