InstanceofCanBeUsed
warning on by default quick-fixGroup: Language level migration · PhpStorm name: InstanceofCanBeUsedInspection
Testing an object's class through string comparisons or reflection-like helpers (get_class($o) === 'Foo', is_a($o, 'Foo'), in_array('Foo', class_parents($o)), …) is slower and less readable than the instanceof operator, and hides the class name from refactoring tools. Suggest instanceof when the subject is known to be a non-string value and the named class exists.
Example
php
<?php
final class Invoice {}
class Document {}
class Receipt extends Document {}
interface Printable {}
function check(Invoice $doc, Document $base, string $name, $loose) {
return [
'Invoice' === get_class($doc),
get_class($doc) <> 'Receipt',
get_parent_class($base) == "Document",
\is_a($doc, 'Invoice', FALSE),
is_subclass_of($base, 'Receipt'),
in_array('Document', class_parents($base), true),
get_class($base) === 'Document',
(get_class($doc)) === 'Invoice',
get_class($name) == 'Invoice',
get_class($loose) == 'Invoice',
is_a($doc, 'Invoice', true),
is_a($doc, 'Foo'),
is_a($doc, '\\Invoice'),
is_a($doc, 'Printable'),
in_array('Invoice', class_implements($name)),
];
}php
<?php
final class Invoice {}
class Document {}
class Receipt extends Document {}
interface Printable {}
function check(Invoice $doc, Document $base, string $name, $loose) {
return [
$doc instanceof \Invoice,
get_class($doc) <> 'Receipt',
get_parent_class($base) == "Document",
$doc instanceof \Invoice,
is_subclass_of($base, 'Receipt'),
in_array('Document', class_parents($base), true),
get_class($base) === 'Document',
(get_class($doc)) === 'Invoice',
get_class($name) == 'Invoice',
get_class($loose) == 'Invoice',
is_a($doc, 'Invoice', true),
is_a($doc, 'Foo'),
is_a($doc, '\\Invoice'),
is_a($doc, 'Printable'),
in_array('Invoice', class_implements($name)),
];
}Reported:
- line 10: Prefer '$doc instanceof \Invoice'.
- line 11: Consider '!$doc instanceof \Receipt' (not an exact equivalent).
- line 12: Consider '$base instanceof \Document' (not an exact equivalent).
- line 13: Prefer '$doc instanceof \Invoice'.
- line 14: Consider '$base instanceof \Receipt' (not an exact equivalent).
- line 15: Consider '$base instanceof \Document' (not an exact equivalent).
Configure
In custos.json:
json
{
"rules": {
"InstanceofCanBeUsed": {
"enabled": false
}
}
}Suppress
Before the statement or declaration (or the first statement of the file), either of:
php
// @custos-ignore InstanceofCanBeUsed
/**
* @noinspection InstanceofCanBeUsedInspection
*/