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 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab