note 112033 added to language.oop5.typehinting

From: Date: Thu, 25 Apr 2013 03:05:30 +0000
Subject: note 112033 added to language.oop5.typehinting
Groups: php.notes 
Request: Send a blank email to php-notes+get-194617@lists.php.net to get a copy of this message
I've implemented a basic function to ensure argument's type. <?php /** * Primary types */ class Type { const SKIP = 0; const INT = 1; const STRING = 2; const BOOLEAN = 3; const CALLBACK = 4; const FLOAT = 5; const RESOURCE = 6; } /** * @throws InvalidArgumentException */ function ensureType() { $debugStack = debug_backtrace(); $argv = $debugStack[1]['args']; $types = func_get_args(); foreach ($argv as $key => $value) { $message = null; if (is_null($value)) { continue; } switch ($types[$key]) { case Type::INT: if (!is_int($value)) { $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be of type int'; } break; case Type::STRING: if (!is_string($value)) { $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be of type string'; } break; case Type::BOOLEAN: if (!is_bool($value)) { $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be of type boolean'; } break; case Type::CALLBACK: if (!is_callable($value)) { $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be a valid callback'; } break; case Type::FLOAT: if (!is_float($value)) { $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be of type float'; } break; case Type::RESOURCE: if (!is_resource($value)) { $message = 'Argument ' . $key . ' passed to ' . $debugStack[1]['function'] . '() must be of type resource'; } break; } if (!is_null($message)) { if (is_object($value)) { $message .= ', instance of ' . get_class($value) . ' given'; } else { $message .= ', ' . gettype($value) . ' given'; } throw new InvalidArgumentException($message); } } } function dummyFunction($var1, $var2, $var3) { ensureType(Type::BOOLEAN, Type::INT, Type::STRING); } $object = new ReflectionClass('ReflectionClass'); dummyFunction(1, $object, 'Hello there'); ---- Server IP: 69.147.83.199 Probable Submitter: 79.112.38.194 ---- Manual Page -- http://php.net/manual/en/language.oop5.typehinting.php Edit -- https://master.php.net/note/edit/112033 Del: integrated -- https://master.php.net/note/delete/112033/integrated Del: useless -- https://master.php.net/note/delete/112033/useless Del: bad code -- https://master.php.net/note/delete/112033/bad+code Del: spam -- https://master.php.net/note/delete/112033/spam Del: non-english -- https://master.php.net/note/delete/112033/non-english Del: in docs -- https://master.php.net/note/delete/112033/in+docs Del: other reasons-- https://master.php.net/note/delete/112033 Reject -- https://master.php.net/note/reject/112033 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#194617) next »