dousong5492 2013-01-31 09:42 采纳率: 100%
浏览 24
已采纳

通过引用传递的PHP局部变量是否可以在函数外部生存?

Basically in the case of working with large arrays it's convenient to pass null back if an error occurs since if $array = null then $array[] = 1 is [ 1 ] and null is also usable in a callable context, ie. function (array $array = null) will accept null as an acceptable value. Basically null is convenient since you can easily identify it as an error if you have error handling code, but also easily ignore it if you don't care.

This is fairly straight forward in most cases, however there is a corner case where PHP doesn't really support it all that well and that's when passing back a reference in the context of a function that doesn't necessarily accept a reference but needs to pass null back sometimes, yet pass a reference back other times (most of the time this is not an issue since you're returning a reference to a instance variable but sometimes that's not the case). There's also the case of calling a function with a null value in a non awkward way.

The reason to pass the reference is obviously to save the trouble of copying the array around (especially when it's very large).

The following "solution"...

\error_reporting(-1);

function & nil()
{
    $nil = null;
    return $nil;
}

function & pass(array & $variable = null)
{
    return $variable;
}

function & check ()
{
    return nil();
}

$test = pass(nil());
$test = &pass(nil());

$test1 = &check();
$test1[] = 1;
$test2 = &check();
$test2[] = 2;

\var_dump($test1, $test2);

Works, but...

My question is Does PHP guarantee the local variable won't be garbage collected before all references to it are garbage collected? or is that undefined behavior.

  • 写回答

1条回答 默认 最新

  • doujue6196 2013-02-01 10:21
    关注

    PHP will never GC anything while reference count is greater than 0.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码