Xdebug作为参考计数工作

时间:2016-10-16 21:52:11

标签: php xdebug

文档中有一些片段说明了这是如何工作的,但有一点不清楚,我在下面说明:

/// Example 1
$a = 10;
xdebug_debug_zval('a');
/// Output:
/// a:(refcount=1, is_ref=0),int 10

/// Example 2
$a = 10;
$b = 10;
xdebug_debug_zval('a','b');
/// Output:
/// a:(refcount=1, is_ref=0),int 10
/// b:(refcount=1, is_ref=0),int 10

/// Example 3
$a = 10;
$b = $a;
xdebug_debug_zval('a','b');
/// Output:
/// a:(refcount=2, is_ref=0),int 10
/// b:(refcount=2, is_ref=0),int 10

/// Example 4
$a = 10;
$b = &$a;
xdebug_debug_zval('a','b');
/// Output:
/// a:(refcount=2, is_ref=1),int 10
/// b:(refcount=2, is_ref=1),int 10

/// Example 5
$a = 10;
$b = $a;
$c = $a;
xdebug_debug_zval('a','b','c');
/// Output:
/// a:(refcount=3, is_ref=0),int 10
/// b:(refcount=3, is_ref=0),int 10
/// c:(refcount=3, is_ref=0),int 10

/// Example 6
$a = 10;
$b = &$a;
$c = $a;
xdebug_debug_zval('a','b','c');
/// Output:
/// a:(refcount=2, is_ref=1),int 10
/// b:(refcount=2, is_ref=1),int 10
/// c:(refcount=1, is_ref=0),int 10

/// Example 7
$a = 10;
$b = &$a;
$c = &$a;
xdebug_debug_zval('a','b','c');
/// Output:
/// a:(refcount=3, is_ref=1),int 10
/// b:(refcount=3, is_ref=1),int 10
/// c:(refcount=3, is_ref=1),int 10

对于我来说最不合逻辑的所有例子都是Example 6,我真的不明白为什么在没有得到以下条目的所有行时我们必须调试

/// Output:
/// a:(refcount=3, is_ref=1),int 10
/// b:(refcount=3, is_ref=1),int 10
/// c:(refcount=3, is_ref=0),int 10

解释是什么事?

1 个答案:

答案 0 :(得分:0)

如果你熟悉它,你必须从C语言的指针来考虑。 PHP中的变量是ZVAL的指针,所以当你" copy" PHP中的变量,PHP 实际上复制了它的值,但增加了引用计数并重复了指针。但是如果你改变原始值,其他值也不会改变,因为PHP会做一些叫做 copy-on-write 的东西(除非refcount = 1,

$a = 10;
$b = $a;  // $b is a soft copy of $a, refcount++
$a = 11;  // $a changes, a new zval is created

虽然:

$a = 10;
$b = &$a; // $b is still a copy of a, but this time a reference
$a = 11;  // $a and $b change

那么你的"示例6"会发生什么?好吧,PHP知道refcount> 1,但你不能"软拷贝" $ a&#; s zval in $ c,因为否则当你改变$ a或$ b时它也会改变$ c的值,所以$ c变成一个新的zval,refcount = 1.

$a = 10;    // new zval created (refcount=1)
$b = &$a;   // $b is a copy of $a but is_ref=1 (and refcount=2)
$c = $a;    // $c is a NEW zval, refcount=1

我害怕我没有好好解释自己:(如果你还有疑问,我可以再试一次。

相关问题