Home  >  Article  >  php教程  >  PHP unset()函数销毁变量

PHP unset()函数销毁变量

WBOY
WBOYOriginal
2016-06-13 11:11:12775browse

我们在学习

PHP unset()函数是用来销毁变量的,但很多时候,这个函数只把变量给销毁了,内存中存放的该变量的值仍然没有销毁,也就是没能达到我们想要的释放内存的效果。这里我建议大家用 $变量=null 的方法来释放其内存。原因看了下面的就知道了。

以下是关于PHP unset()函数的几点要点:(以下均在windows环境下测试,php 2.5.9)

1. 该函数只有在变量值所占空间超过256字节长的时候才会释放内存
2. 只有当指向该值的所有变量(比如有引用变量指向该值)都被销毁后,地址才会被释放(也要执行1的判断)

下面给出例子代码论证:

  1.  ?php  
  2. $test=str_repeat("1",256);  
  3. $s = memory_get_usage();   
  4. //改函数用来查看当前所用内存  
  5. unset($test);  
  6. $e = memory_get_usage();  
  7. echo ' 释放内存: '.($s-$e);   
  8. //输出为272,但如果上面test变量改为
    $
    test=str_repeat("1",255),输出则为0  
  9. ?> 

至于为什么是272而不是256,就不是很清楚了,不知道内部是怎么处理的。

  1.  ?php  
  2. $test = str_repeat("1",256);  
  3. $p = &$test;  
  4. unset($test);  
  5. echo $p;   
  6. //输出为256个1。如果上面改为unset($p)
    ,更不行了,echo $test 直接显示为256个1  
  7. ?> 

也就是说内存中赋给$a的值仍然存在。可见unset()并没达到释放内存的效果。

但如果在上述代码中加入$test=null,或者再加一个unset($p),就能达到释放内存效果了,PHP unset()函数测试代码如下:

变量赋值为null方法:

  1.  ?php  
  2. $test = str_repeat("1",256);  
  3. $p = &$test;  
  4. $s = memory_get_usage();   
  5. $test = null;  
  6. unset($test);  
  7. $e = memory_get_usage();  
  8. echo ' 释放内存: '.($s-$e); 
  9. //输出为272  
  10. var_dump($p); //输出为NULL  
  11. ?> 

将指向该地址中值的变量全部销毁的方法:

  1.  ?php  
  2. $test = str_repeat("1",256);  
  3. $p = &$test;  
  4. $s = memory_get_usage();   
  5. //注意,以下2个unset()顺序对调没
    有关系,不影响结果  
  6. unset($p);  
  7. unset($test);   
  8. $e = memory_get_usage();  
  9. echo ' 释放内存: '.($s-$e); //输出为272  
  10. ?> 

到此PHP unset()函数论证完毕。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn