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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀