PHP在函数结束后立即释放局部变量吗?

前端之家收集整理的这篇文章主要介绍了PHP在函数结束后立即释放局部变量吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
代码更好地说明了我的要求:
  1. function foo(){
  2.  
  3. $var = get_huge_amount_of_data();
  4.  
  5. return $var[0];
  6. }
  7.  
  8.  
  9. $s = foo();
  10.  
  11. // is memory freed here for the $var variable created above?
  12.  
  13. do_other_stuff(); // need memory here lol

所以我知道$var在某些时候会被释放,但PHP是否有效地做到了?或者我手动需要取消设置昂贵的变量?

你可以在类上看到这个例子,因为你可以“捕获”释放类’析构函数中的变量:
  1. class a {
  2. function __destruct(){
  3. echo "destructor<br>";
  4. }
  5. }
  6.  
  7. function b(){ // test function
  8. $c=new a();
  9. echo 'exit from function b()<br>';
  10. }
  11.  
  12. echo "before b()<br>";
  13. b();
  14. echo "after b()<br>";
  15.  
  16. die();

这个脚本输出

  1. before b()
  2. exit from function b()
  3. destructor
  4. after b()

现在很清楚,变量在函数出口处被破坏了.

猜你在找的PHP相关文章