Andrelec1
Andrelec1

Reputation: 382

dynamic (scalar) cast in php

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

Answers (2)

Andrelec1
Andrelec1

Reputation: 382

like @deceze solution ... but directly in phplib http://php.net/manual/en/function.settype.php

Upvotes: 0

deceze
deceze

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

Related Questions