In daily PHP development, we often need to verify whether the variable is an instance of a specific class. Although PHP provides a variety of ways to judge types, such as the instanceof operator, the is_a() function has become the first choice for many developers due to its flexibility and simplicity.
This article will take you step by step to build a simple type verification tool class based on the is_a() function, helping you quickly judge object types and improve code readability and reusability.
is_a() is a built-in function provided by PHP, which is used to determine whether an object belongs to a certain class or a subclass of that class.
bool is_a(object|string $object_or_class, string $class, bool $allow_string = false)
$object_or_class : The object or class name to be checked.
$class : Target class name.
$allow_string : Whether to allow the object name to be passed in strings (for static calls).
We will use the is_a() function to encapsulate a simple tool class TypeChecker to simplify and centrally manage type judgment logic.
<code>
class TypeChecker
{
/**
* Determine whether the object is an instance of a certain class
*
* @param object|string $objectOrClass
* @param string $expectedClass
* @param bool $allowString
* @return bool
*/
public static function isInstanceOf($objectOrClass, string $expectedClass, bool $allowString = false): bool
{
return is_a($objectOrClass, $expectedClass, $allowString);
}
/**
* Batch verification of multiple objects types
*
* @param array $objectsWithExpectedClasses
* @return array
*/
public static function validateMultiple(array $objectsWithExpectedClasses): array
{
$results = [];
foreach ($objectsWithExpectedClasses as $label => [$objectOrClass, $expectedClass]) {
$results[$label] = self::isInstanceOf($objectOrClass, $expectedClass);
}
return $results;
}
}
</code>
This class provides two methods:
isInstanceOf() : Verify the type of a single object.
validateMultiple() : supports batch verification of the correspondence between objects and classes.
Let's take a look at how this tool class is used in actual projects.
<code>
interface LoggerInterface {}
class FileLogger implements LoggerInterface {}
class MailLogger {}
$logger1 = new FileLogger();
$logger2 = new MailLogger();
// Single Verification
if (TypeChecker::isInstanceOf($logger1, LoggerInterface::class)) {
echo "logger1 yes LoggerInterface Examples\n";
}
// Batch Verification
$results = TypeChecker::validateMultiple([
'fileLogger' => [$logger1, LoggerInterface::class],
'mailLogger' => [$logger2, LoggerInterface::class],
]);
print_r($results);
</code>
The output result is as follows:
logger1 yes LoggerInterface Examples
Array
(
[fileLogger] => 1
[mailLogger] =>
)
Suppose you are developing a factory class that dynamically loads the class from the configuration file and instantiates the object. You can use TypeChecker to ensure that these classes implement the desired interface and avoid type errors at runtime.
<code>
class LoggerFactory
{
public static function create(string $className): LoggerInterface
{
$instance = new $className();
if (!TypeChecker::isInstanceOf($instance, LoggerInterface::class)) {
throw new InvalidArgumentException("kind $className Must be achieved LoggerInterface interface");
}
return $instance;
}
}
$logger = LoggerFactory::create('FileLogger'); // normal
$logger = LoggerFactory::create('MailLogger'); // throw an exception
</code>
Encapsulating a simple type verification tool class through is_a() can greatly improve the robustness and readability of the code. Whether it is for basic type detection in small and medium-sized projects, or as a security checking layer in large frameworks, it can come in handy.
If you want to further build a complete verification system, you can even add logic such as URL source and dependency injection classes to verify. For example, verifying in the service registry whether a class implements the necessary interface or inherits a specific base class can prevent hidden errors in the business logic: