您是否也在为如何将参数发送到 FILTER_CALLBACK 而苦恼?
假设您想拥有一组自定义过滤器,您可以在 filter_var、filter_var_array 等等中使用它们,但您希望能够像在 filter_var 中一样用不同的参数调用这些新的过滤器。
最简单的方法是创建一个包含所有自定义过滤器的类。然后在 filter_var 参数数组中用您的参数构造这个类,并在其中输入您想运行的方法。
如果您将参数发送为数组,则可以轻松地进行默认值设置。但是您可以通过此解决方案传递任意数量的参数,无论它们是什么类型。
例子
<?php
class CustomFilters {
private $options = array();
public function __construct(array $options=array()){
$this->options = $options;
}
private function get_options(array $defaults){
return array_merge($defaults, $this->options);
}
public function FILTER_STEP_RANGE($val){
$options = $this->get_options(
array(
"min_range" => 1,
"max_range" => 10,
"step" => 1,
"default" => null, "strict" => false, "cast" => false )
);
if(in_array( $val, range($options["min_range"], $options["max_range"], $options["step"]), $options["strict"])){
if( $options["cast"] && !settype($val, $options["cast"])) {
return $options["default"];
}
return $val;
}else{
return $options["default"];
}
}
public function FILTER_ENUM($val){
$options = $this->get_options(
array(
"values" => array(),
"strict" => false, "default" => null, "cast" => false )
);
if(in_array($val, $options["values"], $options["strict"])){
if( $options["cast"] && !settype($val, $options["cast"])){
return $options["default"];
}
return $val;
}else{
return $options["default"];
}
}
}
$data = array(
"range1" => "200",
"range2" => 25,
"enum" => "yes"
);
$args = array(
"range1" => array(
"filter" => FILTER_CALLBACK,
"options" => array(
new CustomFilters(array( "min_range" => 10, "max_range" => 600, "step" => 10, "default" => 120,
"cast" => "integer")),
'FILTER_STEP_RANGE'
)
),
"range2" => array(
"filter" => FILTER_CALLBACK,
"options" => array(
new CustomFilters(array( "min_range" => 0, "max_range" => 1, "step" => .1, "default" => .5,
"cast" => "float")),
'FILTER_STEP_RANGE'
)
),
"enum" => array(
"filter" => FILTER_CALLBACK,
"options" => array(
new CustomFilters(array( "values" => array("yes", "no", "Yes","No"), "cast" => "string")),
'FILTER_ENUM'
)
)
);
var_dump( filter_var_array($data, $args) );
?>
返回值
array(3) {
["range1"] => int(200)
["range2"] => float(0.5)
["enum"] => string(3) "yes"
}