PHP 使用默认值过滤回调

PHP filter callback with 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 选项。因此,为回调过滤器设置默认值应该不是什么超自然的事情。我是否遗漏了一些明显的东西?

谢谢

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

所以如果你想保证自定义回调总是被调用,即使输入数组不包含键=>值对,你可以这样做:

$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
        }
    ]
]);