2016-12-16 66 views
1

使用filter_var_arrayFILTER_CALLBACK時,有沒有辦法定義默認值(或強制每次調用回調)?使用默認值的PHP過濾回調

實施例的數據:

{ 
    "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選項。因此,回調過濾器的默認值不應該超自然。我錯過了明顯的東西嗎?

感謝

+0

不認爲這是可能的。它應該過濾現有的數據,而不是無中生有...... – Narf

+0

看來你是對的。缺省值僅在驗證程序(布爾,int等)不驗證輸入時纔有效。如果輸入不在這裏(即使TRUE是filter_var_array的3參數)。謝謝 – rekam

回答

0

確定,所以經過一些意見和挖掘,在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 
     } 
    ] 
]);