Skip to content

Instantly share code, notes, and snippets.

@dhrrgn
Last active January 14, 2022 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhrrgn/11271702 to your computer and use it in GitHub Desktop.
Save dhrrgn/11271702 to your computer and use it in GitHub Desktop.
PHP Type Check Function
<?php
/**
* Checks the type of the given value against an array of valid types.
*
* If the value is a valid type, `true` is returned, if not, an
* InvalidArgumentException is thrown.
*
* // Throws: Invalid type: string, Expected type(s): array, ArrayAccess
* checktype('foo', ['array', 'ArrayAccess']);
*
* @param mixed $value
* @param array $validTypes
* @return bool
* @throws \InvalidArgumentException
*/
function checktype($value, array $validTypes)
{
$nativeTypes = [
'array' => 'is_array',
'bool' => 'is_bool',
'callable' => 'is_callable',
'double' => 'is_double',
'float' => 'is_float',
'int' => 'is_int',
'integer' => 'is_integer',
'long' => 'is_long',
'null' => 'is_null',
'numeric' => 'is_numeric',
'object' => 'is_object',
'real' => 'is_real',
'resource' => 'is_resource',
'scalar' => 'is_scalar',
'string' => 'is_string',
];
$valid = false;
foreach ($validTypes as $type) {
if (isset($nativeTypes[$type])) {
$valid = call_user_func($nativeTypes[$type], $value);
} else {
$valid = $value instanceof $type;
}
if ($valid) {
break;
}
}
if (!$valid) {
$type = gettype($value);
if (gettype($value) === 'object') {
$type = get_class($value);
}
throw new InvalidArgumentException('Invalid type: '.$type.', Expected type(s): '.implode(', ', $validTypes));
}
return true;
}
@dhrrgn
Copy link
Author

dhrrgn commented Apr 24, 2014

If you are curious as to why I went with checktype as the name, it is so it was consistent with the native gettype function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment