Reputation: 382
I need to cast value in type define in string. For the moment i use this:
/**
* @param mixed $val
* @param string $type
*
* @return bool|float|int|string
*/
protected function castTo($val, $type)
{
switch ($type) {
case 'boolean':
case 'bool':
return (boolean) $val;
case 'integer':
case 'int':
return (int) $val;
case 'string':
return (string) $val;
case 'double':
case 'float':
return (float) $val;
default:
return $val;
}
}
But do you know a better solution ( in php 5.6 and 7+ ) ?
Upvotes: 1
Views: 332
Reputation: 382
like @deceze solution ... but directly in phplib http://php.net/manual/en/function.settype.php
Upvotes: 0
Reputation: 522110
Use the function equivalents like intval
to get a "dynamic handle":
$funcs = ['boolean' => 'boolval', 'integer' => 'intval', 'string' => 'strval', 'float' => 'floatval', ...];
if (!array_key_exists($type, $funcs)) {
return $val;
} else {
return call_user_func($funcs[$type], $val);
}
Note that this may be shorter, but not necessarily overall better than a switch
…
Upvotes: 1