Skip to main content

How to Check an Object's Class in PHP with instanceof

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

$value instanceof ClassName in PHP is true when $value is an object of that class, of a class that extends it, or of a class that implements it as an interface. For anything that isn't an object, such as a string, it's simply false, with no error.

Syntax​

Syntax
$<result> = $<value> instanceof <ClassName>;
PartWhat it does
$<value>The value to check. It can be of any type.
<ClassName>A class or interface name, such as stdClass.
$<result>true if $<value> is an object of that class, otherwise false.

The PHP manual: "instanceof is used to determine whether a PHP variable is an instantiated object of a certain class", and "instanceof does not throw any error if the variable being tested is not an object, it simply returns false."

The Example​

The example defines an empty class, Plan, and makes one. It also decodes a JSON object, which json_decode turns into a stdClass object, PHP's plain object with no class of its own. It checks both against Plan and stdClass, checks a string, and reads a property from the decoded value only when it's a stdClass. Then the JSON turns out to be a string, and the code reads the property without checking.

Prerequisites​

  • PHP. This guide uses PHP 8.6.0.

Step 1: Write the Code​

Create a file named main.php:

main.php, which declares an empty Plan class, makes a Plan, decodes a JSON object and sets a string, prints four instanceof checks with var_dump, then echoes the decoded name only when the decoded value is a stdClass.

main.php
<?php

declare(strict_types=1);

class Plan
{
}

$plan = new Plan();
$decoded = json_decode('{"name":"pro"}'); // a JSON object becomes a stdClass object
$name = 'pro';

var_dump($plan instanceof Plan);
var_dump($decoded instanceof stdClass);
var_dump($decoded instanceof Plan);
var_dump($name instanceof Plan); // not an object at all: false, with no error

// Check that it's an object before reading a property from it.
if ($decoded instanceof stdClass) {
echo $decoded->name . "\n";
}

new Plan() makes an object of the class Plan. var_dump prints a value with its type, so true shows as bool(true).

Step 2: Run It​

Terminal
php main.php
Output
bool(true)
bool(true)
bool(false)
bool(false)
pro

The command is the same in zsh, bash and PowerShell.

Step 3: Remove the Check​

Replace main.php with a version whose JSON is a string, and which reads the property without checking:

main.php
<?php

declare(strict_types=1);

$decoded = json_decode('"pro"'); // this JSON is a string, not an object
// Without the instanceof check, a property is read from a string.
echo $decoded->name . "\n";
Terminal
php main.php
Output
PHP Warning: Attempt to read property "name" on string in /Users/Shared/you/main.php on line 7

Warning: Attempt to read property "name" on string in /Users/Shared/you/main.php on line 7

A zsh terminal where php main.php prints bool(true) twice, bool(false) twice and pro; for the changed file it prints PHP Warning: Attempt to read property "name" on string on line 7, twice.

What Happened​

  • $plan instanceof Plan and $decoded instanceof stdClass were true.
  • $decoded instanceof Plan was false: a stdClass object isn't a Plan.
  • $name instanceof Plan was false, with no error, because $name is a string, not an object.
  • The if read $decoded->name only after the check, and printed pro.
  • Without the check, $decoded was the string 'pro', because the JSON "pro" is a string. Reading ->name from a string printed Warning: Attempt to read property "name" on string and gave null, which echo printed as an empty line.
  • The warning appears twice because this PHP's settings both log errors to the terminal, as PHP Warning:, and display them, as Warning:.

Common Mistakes​

MistakeWhat happensDo this instead
Reading a property from a decoded value without checking itA string or null gives a warning and nullCheck instanceof stdClass first
Misspelling the class name, as in instanceof StdClasThe check is false, with no error, so it never passesCheck the class name's spelling
Expecting instanceof to fail for an object of a child classIt's true for child classes and for interfaces the class implementsCompare get_class($value) when you need the exact class

Troubleshooting​

SymptomLikely causeFix
Warning: Attempt to read property "name" on stringThe value isn't an objectCheck it with instanceof before reading a property
An instanceof check that's never trueThe class name is misspelled, or the value isn't an objectCheck the name, and var_dump the value

FAQ​

Does instanceof work with parent classes and interfaces?​

Yes. In my check, an object of ProPlan, a class declared class ProPlan extends Plan {}, was an instanceof Plan, and new ArrayObject([]) was an instanceof Countable, an interface it implements.

Do I need parentheses in !$x instanceof Foo?​

No. The PHP manual says "!$x instanceof Foo is grouped as !($x instanceof Foo)". In my check, !$decoded instanceof stdClass and !($decoded instanceof stdClass) gave the same result. The parentheses make it easier to read, though.

Can the class name be in a variable?​

Yes. With $class = 'stdClass';, json_decode('{}') instanceof $class was true.

Conclusion​

instanceof tells you whether a value is an object of a class, a child class or an interface. It never throws for strings or other non-objects, so use it to check a decoded value before reading its properties.

Additional Resources​