I'm currently working on a framework and started to crash ... how should I handle the wrong parameter types when someone calls a function within?
Example:
function example1($title, $comment_num) {
$title = (string) $title;
$comment_num = (int) $comment_num;
}
or
function example2($title, $comment_num) {
if (!is_string($title)) {
trigger_error('String expected for first parameter', E_USER_WARNING);
return;
}
if (!is_string($title)) {
trigger_error('Int expected for second parameter', E_USER_WARNING);
return
}
}
Or will a mixture of both work? Throw an error and convert the type anyway?
What would be the best way to do this? I plan to release it so that it doesn’t just use it, so I want to think of a better way for others. Thank.
CHANGE !!!
So, I decided to give an answer, but I also wanted to publish the code that I did, which allows me to quickly check types. Its abit is rude, but it works quite well.
function __type_check($params) {
if (count($params) < 1) {
return;
}
$types = func_get_args();
array_shift($types);
$backtrace = debug_backtrace();
$backtrace = $backtrace[1];
$global_types = array(
'bool' => 'boolean',
'int' => 'integer',
'float' => 'double'
);
$error = false;
for ($i = 0, $j = count($types); $i < $j; ++$i) {
if (strpos($types[$i], ',') === false) {
$type = strtolower($types[$i]);
if (isset($global_types[$type])) {
$type = $global_types[$type];
}
if (gettype($params[$i]) != $type) {
$error = true;
break;
}
} else {
$current_types = array_map('trim', explode(',', $types[$i]));
foreach ($current_types as $type) {
$type = strtolower($type);
if (isset($global_types[$type])) {
$type = $global_types[$type];
}
if (gettype($params[$i]) == $type) {
continue 2;
}
}
$error = true;
break;
}
}
if ($error) {
trigger_error($backtrace['function'] . '() expects parameter ' . ($i + 1) . ' to be ' . $types[$i] . ', ' . gettype($params[$i]) . ' given', E_USER_WARNING);
return false;
}
return true;
}
And you will use it as follows:
function string_manipulation($str, $str2, $offset = 1) {
if (!__type_check(func_get_args(), 'string', 'string', 'int,float')) {
return false;
}
}
, , - . 'string, int, array, object' .., gettype
/* */
null - , ,
, , typecheck
havent ... meh
, : D