1.2.72. Avoid get_class()

get_class() should be replaced with the instanceof operator to check the class of an object.

get_class() only compares the full namespace name of the object’s class, while instanceof actually resolves the name, using the local namespace and aliases.

<?php

    use Stdclass as baseClass;

    function foo($arg) {
        // Slow and prone to namespace errors
        if (get_class($arg) === 'Stdclass') {
            // doSomething()
        }
    }

    function bar($arg) {
        // Faster, and uses aliases.
        if ($arg instanceof baseClass) {
            // doSomething()
        }
    }
?>

See also get_class and Instanceof.

1.2.72.1. Suggestions

  • Replace get_class() with the instanceof operator

1.2.72.2. Specs

Short name

Structures/UseInstanceof

Rulesets

All, Analyze, CE, CI-checks, Changed Behavior

Exakat since

0.8.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

class, type

Available in

Entreprise Edition, Community Edition, Exakat Cloud