为什么引用计数是2而不是1? [英] Why the refcount is 2 not 1?

查看:148
本文介绍了为什么引用计数是2而不是1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $var = 1;
  debug_zval_dump($var);

输出:

long(1) refcount(2)


  $var = 1;
  $var_dup = &$var;
  debug_zval_dump($var);exit;

输出:

long(1) refcount(1)

更新

对答案非常失望...

Very disapointed at the answer...

推荐答案

无效 debug_zval_dump (混合的 $ variable );

代码:

$var = 1;              # $var's Refcount = 1
debug_zval_dump($var); # $var is passed by refrence intarlly.

输出:

long(1) refcount(2)

说明: 由于$ var的refcount为1,PHP会对此进行优化并直接处理内存,而不是进行复制,因为没有机会污染任何其他引用. PHP内部通过引用传递$ var,以便它也可以在需要时直接编辑内存.第二个引用是在实际调用debug_zval_dump()时创建的.

Explanation: As $var's refcount is 1, PHP optimizes this and handles the memory directly instead of making a copy because there is no chance of contaminating any other references. PHP internally passing $var by reference, so that it can edit the memory directly if it needs too. The second reference is created when actually calling debug_zval_dump().

这里的引用计数为2极不明显.那是怎么回事?

A refcount of 2, here, is extremely non-obvious. So what's happening?

当变量具有单个引用时(就像$ var在用作debug_zval_dump()的参数之前一样),PHP的引擎会优化将其传递给函数的方式.在内部,PHP将$ var像引用一样对待(因为在此函数的作用域中增加了refcount),但需要注意的是,如果恰好将传递的引用写入到文件中,则会进行复制,但仅在编写时.这就是所谓的写时复制".

When a variable has a single reference (as did $var before it was used as an argument to debug_zval_dump()), PHP's engine optimizes the manner in which it is passed to a function. Internally, PHP treats $var like a reference (in that the refcount is increased for the scope of this function), with the caveat that if the passed reference happens to be written to, a copy is made, but only at the moment of writing. This is known as "copy on write."

因此,如果debug_zval_dump()恰好写入其唯一参数(并且没有写入),那么将创建一个副本.在此之前,该参数一直是引用,导致在函数调用范围内,引用计数增加为2.

So, if debug_zval_dump() happened to write to its sole parameter (and it doesn't), then a copy would be made. Until then, the parameter remains a reference, causing the refcount to be incremented to 2 for the scope of the function call.

代码:

$var = 1;              # $var's Refcount = 1
$var_dup = &$var;      # $var's Refcount = 2
debug_zval_dump($var); # A copy is passed as $var's refcount is 2.

输出:

long(1) refcount(1)

说明: 这一次在调用函数时将复制$ var.这是因为$ var被两次引用,并且PHP不想污染任何其他引用,因此它会复制$ var以使其自身能够继续工作.由于现在有一个单独的内存仅用于函数调用的范围,因此它只有一个引用,它就是自我.因此,对于该函数的范围,副本的引用计数为1(它是自身的).

Explanation: This time a copy of $var is being made when the function is called. This is because $var is referenced twice and PHP does not want to contaminate any other references so it makes a copy of $var for it's self to work on. As there is now a separate piece of memory that is only used for the scope of the function call it only has one refrence, it's self. So for the scope of the function the copy's refcount is 1 (it's self).

这篇关于为什么引用计数是2而不是1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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