我很困惑,到底是什么,你如何使用它在您的表单处理。它是否只删除不在$expected[]中的不需要的$_POST条目?我还应该使用$_POST['carModel']来获取值吗?或许还有更好的办法?
<?php
$expected = array( 'carModel', 'year', 'bodyStyle' );
foreach( $expected AS $key ) {
if ( !empty( $_POST[ $key ] ) ) {
${$key} = $_POST[ $key ];
}
else
{
${$key} = NULL;
}
}
?>
它创建变量$carModel, $year等对应的POST字段的内容,如果没有,则为空。
<?php
// builds an array
$expected = array( 'carModel', 'year', 'bodyStyle' );
// loops over the array values (carModel, year...)
foreach( $expected AS $key ) {
// checks, if this key is found in the incoming POST array and not empty
if ( !empty( $_POST[ $key ] ) ) {
// assigns the value of POST, to a variable under the key name
${$key} = $_POST[ $key ];
} else {
${$key} = NULL;
}
}
?>
$expected数组的目的是为POST数组键提供一个白名单。有更好的方法来实现这一点,特别是filter_input(), filter_input_array()。
示例代码http://www.php.net/manual/en/function.filter-input-array.php
对,伪代码${$variable}是创建一个新变量,也就是:
$variable = 'carModel';
$value = 'VW'
${$variable} = $value;
将$_POST[$key]赋值给$test,如$test = $_POST[$key];echo $未来;//$_POST['future']
现在您可以跳过使用$_POST['test']来使用$test,白名单中的所有数组键都应该分配给由键名调用的变量;
在您的示例中,$ exception像过滤器一样只分配这个数组
如果post数据如示例
$_POST["carModel"] = "BMW";
$_POST["year"] = 2013;
这将意味着…
$carModel = "BMW";
$year = 2013;
$bodyStyle = null;
与
相同extract( $_POST );