PHP过滤器回调,默认值为

时间:2016-12-16 10:46:35

标签: php filter callback default-value

使用filter_var_arrayFILTER_CALLBACK时,有没有办法定义默认值(或强制每次调用回调)?

示例数据:

{
    "name": "John"
}

使用示例:

$params = filter_var_array($datas_from_above, [
    'name' => FILTER_SANITIZE_STRING,
    'age' => [
        'filter' => FILTER_CALLBACK,
        'options' => function ($data) {
            // I was thinking $data would be null here
            // but this function is not called if the 
            // param is not present in the input array.
            die('stop?');
        }
    ]
], true); // Add missing keys as NULL to the return value

使用其他过滤器时,有default选项。因此,回调过滤器的默认值不应该是超自然的。我错过了一些明显的东西吗?

由于

1 个答案:

答案 0 :(得分:0)

好吧,经过一些评论和挖掘后,php中的过滤器只处理输入数组包含的内容。

因此,如果您想保证始终调用自定义回调,即使输入数组不包含key =>值对,你可以这样做:

$partial_input = ["name" => "John"]; // E.g. from a GET request
$defaults = ["name" => null, "age" => null];

$input = array_merge($defaults, $partial_input);

$parsed = filter_var_array($input, [
    "name" => FILTER_SANITIZE_STRING,
    "age" => [
        "filter" => FILTER_CALLBACK,
        "options" => function ($data) {
            // do something special if $data === null
        }
    ]
]);