函数结束后,PHP是否会立即释放局部变量? [英] Does PHP free local variables immediately after the function ends?

查看:467
本文介绍了函数结束后,PHP是否会立即释放局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码可以更好地说明我的要求:

The code illustrates better what I'm asking:

function foo(){

  $var = get_huge_amount_of_data();

  return $var[0];
}


$s = foo();

// is memory freed here for the $var variable created above?

do_other_stuff(); // need memory here lol

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

So I know that $var gets freed at some point, but does PHP do it efficiently? Or do I manually need to unset expensive variables?

推荐答案

您可以在类上看到此示例,这是因为您可以捕获"释放类的析构函数中的变量:

You can see this example on a class, that's because you can "catch" freeing a variable in class' destructor:

class a {
  function __destruct(){
    echo "destructor<br>";
  }
}

function b(){ // test function
  $c=new a();
  echo 'exit from function b()<br>';
}

echo "before b()<br>";
b();
echo "after b()<br>";

die();

此脚本输出:

before b()
exit from function b()
destructor
after b()

因此现在很明显,变量在函数出口处被销毁了.

So it is now clear that variables are destroyed at function exit.

这篇关于函数结束后,PHP是否会立即释放局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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