3

在 PHP5 中,当作为参数传递或分配给变量时,字符串是否被引用或复制?

4

2 回答 2

7

debug_zval_dump()功能可能会帮助您回答这个问题。


例如,如果我运行以下代码部分:

$str = 'test';
debug_zval_dump($str);      // string(4) "test" refcount(2)

my_function($str);
debug_zval_dump($str);      // string(4) "test" refcount(2)

function my_function($a) {
    debug_zval_dump($a);    // string(4) "test" refcount(4)
    $plop = $a . 'glop';
    debug_zval_dump($a);    // string(4) "test" refcount(4)
    $a = 'boom';
    debug_zval_dump($a);    // string(4) "boom" refcount(2)
}

我得到以下输出:

string(4) "test" refcount(2)
string(4) "test" refcount(4)
string(4) "test" refcount(4)
string(4) "boom" refcount(2)
string(4) "test" refcount(2)


所以,我会说:

  • 字符串被“引用”,当传递给函数时(并且,可能,当分配给变量时)
  • 但不要忘记 PHP 确实在写入时复制


有关更多信息,这里有几个可能有用的链接:

于 2011-03-11T20:51:59.257 回答
1

它们是副本或取消引用。

于 2011-03-11T20:50:59.083 回答