从一个类型向另一个类型进行类型转换时,如何输入PHP类型作为参数?

时间:2018-08-30 03:43:44

标签: php

我有以下代码:

$limit          = (int)    $request->input('limit');
$offset         = (int)    $request->input('offset');
$page           = (int)    $request->input('page');
$orderBy        = (string) $request->input('order_by');
$orderDirection = (string) $request->input('order_direction');
$filters        = (string) $request->input('filters');

我想具有系统地分配和转换值的功能。例如:

function castValues($myArray)
{
    $urlQueryParams = [];
    foreach ($myArray as $value => $type
    {
        $urlQueryParams[$value] = ($type) $request->input($value);
    }

    return $urlQueryParams;
}

$params = $this->castValues(['limit' => int, 'offset' => 'int', ...]);

如何将$type分配为数据类型(intstring,...)?

1 个答案:

答案 0 :(得分:0)

您可以使用settype

$request = ['limit' => '324', 'offset' => '34'];
function castValues($myArray) {
    global $request;

    $urlQueryParams = [];
    foreach ($myArray as $key => $type) {
        settype($request[$key], $type);
        $urlQueryParams[$key] = $request[$key];
    }

    return $urlQueryParams;
} 

$params = castValues(['limit' => 'int', 'offset' => 'int']);
var_dump($params);

输出

array(2) { ["limit"]=> int(324) ["offset"]=> int(34) }