Unset all variables in PHP script

最后都变了- 提交于 2019-12-18 12:27:29

问题


Trying to unset automatically all variables in script.

Have tried this way:

  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());

Why does it not work?

Is there a better way to do this?

Thanks for helping!

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


回答1:


Here ya go ->

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

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 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.




回答2:


foreach (array_keys($GLOBALS) as $k) unset($$k); unset($k);




回答3:


don't know about you guys, but $$vars doesn't work for me.

that's how I did it.

$vars = array_keys(get_defined_vars());
foreach($vars as $var) {
    unset(${"$var"});
}


来源:https://stackoverflow.com/questions/26247974/unset-all-variables-in-php-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!