在PHP中,是否可以使用字符串设置变量名?

In PHP, is it possible to set a variable name using a string?

我有一段代码像

$id = $_POST['id'];
$name = $_POST['name'];
$story = $_POST['story'];
$imgurl = $_POST['imgurl'];
$thisAction = $_POST['thisAction'];

如您所见,我使用的变量名称等于 $_POST 数组的键。是否可以通过循环完成上述操作?

是的,可以使用 variable variables

foreach($_POST as $key => $value) {
    $$key = $value;
}

或使用extract

extract($_POST);

但请注意,这样做会引入潜在的安全漏洞

其实就像simulating PHP's register_globals directive, which introduces lots of security issues.


您可以分配 $_POST 个变量的子集,这是一种更安全的方法:

$keys = array('id', 'name', 'story', 'imgurl', 'thisAction');
foreach($keys as $key) {
    $$key = $_POST[$key];
}

或使用extract

$whitelisted = array_intersect_key($_POST, array('id', 'name', 'story', 'imgurl', 'thisAction')); 
extract($whitelisted);