【问题标题】:In PHP, is it possible to set a variable name using a string?在 PHP 中,是否可以使用字符串设置变量名?
【发布时间】:2015-08-21 01:05:03
【问题描述】:

我有一段类似的代码

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

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

【问题讨论】:

  • 它叫做“变量”,请不要去那里。使用 $_POST['id'] 有什么问题?
  • @MarcB 我不想多次使用$_POST['id'],因为那样效率很低。最好保存它返回的值的副本。
  • 除了在 tyipng 时保存几个字符之外,在任何地方复制 $id 会更有效率吗?
  • 将它分配给变量$id = isset($_POST['id']) ? $_POST['id'] : 0; 并完成它。不过,不确定如何更有效。编辑:又慢了...
  • 你过度优化了。您将节省的几微秒可以更好地用于优化实际问题,

标签: php algorithm design-patterns optimization


【解决方案1】:

是的,可以使用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);

【讨论】:

  • 替代/附加添加可以是通过EXTR_SKIP进行提取。
猜你喜欢
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多