Using instanceof Operator with Expressions in PHP 8.0

The instanceof operator allows to check if an object is an instance of a class or that class implements an interface. In versions prior to PHP 8.0, the instanceof operator can only be used with identifiers.

Let’s say we have a NumberGenerator class.

NumberGenerator.php

<?php

class NumberGenerator {}

Then we create an object of a class and use instanceof operator to determine whether an object is an instance of that class. All the following use cases of instanceof operator are valid:

main.php

<?php

require_once 'NumberGenerator.php';

$gen = new NumberGenerator();

$test1 = $gen instanceof NumberGenerator; // true

$className = NumberGenerator::class;
$test2 = $gen instanceof $className;      // true

$prefix = 'Number';
$service = 'Generator';
$className = $prefix.$service;
$test3 = $gen instanceof $className;      // true

However, in versions prior to PHP 8.0, the instanceof operator cannot be used with expressions. It means that the following use cases of instanceof operator are invalid:

main.php

<?php

require_once 'NumberGenerator.php';

$gen = new NumberGenerator();

$test1a = $gen instanceof 'NumberGenerator';        // Parse error
$test1b = $gen instanceof ('NumberGenerator');      // Parse error

$test2a = $gen instanceof NumberGenerator::class;   // Parse error
$test2b = $gen instanceof (NumberGenerator::class); // Parse error

$prefix = 'Number';
$service = 'Generator';
$test3a = $gen instanceof $prefix.$service;         // Valid, but is the same as:
                                                    // ($gen instanceof $prefix).$service
$test3b = $gen instanceof ($prefix.$service);       // Parse error
$test3c = $gen instanceof 'Number'.$service;        // Parse error
$test3d = $gen instanceof ('Number'.$service);      // Parse error

Since PHP 8.0, the instanceof operator can be used with expressions using the following syntax:

$object instanceof (expression)

So, in PHP 8.0 or newer versions, all the following use cases of instanceof operator are valid:

main.php

<?php

require_once 'NumberGenerator.php';

$gen = new NumberGenerator();

$test1 = $gen instanceof ('NumberGenerator');      // true

$test2 = $gen instanceof (NumberGenerator::class); // true

$prefix = 'Number';
$service = 'Generator';
$test3a = $gen instanceof ($prefix.$service);      // true
$test3b = $gen instanceof ('Number'.$service);     // true

Leave a Comment

Your email address will not be published. Required fields are marked *