PHP5中是否引用了字符串?

pyo*_*yon 3 php string reference-counting

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

Pas*_*TIN 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)
}
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

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)
Run Code Online (Sandbox Code Playgroud)


所以,我会说:

  • 字符串被"refcounted"传递给函数(并且可能在分配给变量时)
  • 但是不要忘记PHP会在写入时复制


有关更多信息,以下是一些可能有用的链接: