1.2.1273. Unresolved Instanceof

The instanceof operator doesn’t confirm if the compared class exists.

It checks if an variable is of a specific class. However, if the referenced class doesn’t exist, because of a bug, a missed inclusion or a typo, the operator always fails, without a warning. Make sure the following classes are well defined.

<?php

namespace X {
    class C {}

    // This is OK, as C is defined in X
    if ($o instanceof C) { }

    // This is not OK, as C is not defined in global
    // instanceof respects namespaces and use expressions
    if ($o instanceof \C) { }

    // This is not OK, as undefinedClass
    if ($o instanceof undefinedClass) { }

    // This is not OK, as $class is now a full namespace. It actually refers to \c, which doesn't exist
    $class = 'C';
    if ($o instanceof $class) { }
}
?>

See also Instanceof.

1.2.1273.1. Suggestions

  • Remove the call to instanceof and all its dependencies.

  • Fix the class name and use a class existing in the project.

1.2.1273.2. Specs

Short name

Classes/UnresolvedInstanceof

Rulesets

All, Analyze, Changed Behavior, Dead code, Top10

Exakat since

0.8.4

PHP Version

All

Severity

Major

Time To Fix

Instant (5 mins)

Precision

Very high

Features

instanceof

ClearPHP

no-unresolved-instanceof

Examples

WordPress

Available in

Entreprise Edition, Exakat Cloud