取消PHP脚本中的所有变量 [英] Unset all variables in PHP script

查看:51
本文介绍了取消PHP脚本中的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试自动设置脚本中的所有变量.

Trying to unset automatically all variables in script.

尝试过这种方式:

  echo '<br /> Variables in Script before unset(): <br />';
  print_r(array_keys(get_defined_vars()));
  echo '<br /><br />';
  var_dump(get_defined_vars());

  // Creates string of comma-separated variables(*) for unset.
  $all_vars = implode(', $', array_keys(get_defined_vars()));

  echo '<br /><br />';
  echo '<br />List Variables in Script: <br />';
  echo $all_vars;
  unset($all_vars);

  echo '<br /><br />';
  echo '<br />Variables in Script after unset(): <br />';
  print_r(array_keys(get_defined_vars()));
  echo '<br />';
  var_dump(get_defined_vars());

为什么它不起作用?

有更好的方法吗?

感谢您的帮助!

(*) It's seems somewhat that it does not really create the variables, but a string that looks like variables...

推荐答案

在这里->

$vars = array_keys(get_defined_vars());
for ($i = 0; $i < sizeOf($vars); $i++) {
    unset($$vars[$i]);
}
unset($vars,$i);

为了澄清起见,implode返回以相同顺序的所有数组元素的字符串表示形式". http://php.net/manual/en/function.implode.php

And to clarify, implode returns "a string representation of all the array elements in the same order". http://php.net/manual/en/function.implode.php

Unset需要实际变量作为参数,而不仅仅是字符串表示形式.这类似于get_defined_vars()返回的结果(不是实际的变量引用).因此,代码将遍历字符串数组,并使用前面的额外$返回每个引用作为参考-unset可以使用.

Unset requires the actual variable as a parameter, not just a string representation. Which is similiar to what get_defined_vars() returns (not the actual variable reference). So the code goes through the array of strings, and returns each as a reference using the extra $ in front - which unset can use.

这篇关于取消PHP脚本中的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆