Is_Subclass_Of() in PHP
Inheriting classes is an incredibly powerful feature in PHP, but if you’re not careful, it can lead to some very strange behavior. It’s also easy to get lost when trying to figure out whether an object is a descendant of a specific class or not. This article covers a simple function in PHP that will help you determine this, called is_subclass_of().
PHP’s is_subclass_of() function takes two parameters: an object (or the name of a class) and the parent class of that object. If the object is a subclass of the specified class, it will return true; otherwise, it will return false.
Aside from is_subclass_of(), PHP also offers a few other useful functions for narrowing types:
is_superclass_of() - Returns whether an object is superclass of a specified class. This is equivalent to is_subclass_of() except that it takes a class name as the first parameter rather than an object instance.
instanceof - Checks if the object is an instance of a given class. This is similar to is_subclass_of() but works for both objects and classes, even abstract and interface ones.
is_a() - This used to be the preferred way of checking if a class was an instance of another, but it has since been deprecated in favor of instanceof. However, it’s still supported for backward compatibility.
Besides using these functions, you can also use type-specifying annotations like @phpstan-assert, or custom PHPDoc tags to tell the analyzer how to narrow types. Finally, many libraries that perform type-specifying analysis such as webmozart/assert and beberlei/assert support PHPStan plugins to add custom narrowing for methods and return values.