PHP Type Checking

Here’s a quick and dirty utility method for type checking an object or an array of objects.PHP Type checking
[cc escaped=”true” lang=”php”]/**
* Ensure the object (or the first item in the
* array of objects) is of the specified type
* or throw an exception
* @static
* @throws Exception if wrong type
* @param $object_or_array
* @param $class_name
* @return bool
*/
public static function validate_instance_of($object_or_array, $class_name) {
if(is_array($object_or_array)) {
$to_test = $object_or_array[0];
} else {
$to_test = $object_or_array;
}
if(!is_null($to_test) && !($to_test instanceof $class_name)) {
throw new Exception(‘Object or array of objects expected to be of type ‘ . $class_name . ‘, ‘ . gettype($to_test) . ‘ received.’);
}
}[/cc]

It's only fair to share...Buffer this pageShare on Facebook0Tweet about this on TwitterShare on Google+0Share on LinkedIn0Share on Reddit0Pin on Pinterest0Email this to someone
About

Just a guy with strong interest in PHP and Web technologies

Tagged with: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*