isekaijin
isekaijin

Reputation: 19762

Are strings referenced in PHP5?

Are strings referenced or copied, when passed as arguments or assigned to variables, in PHP5?

Upvotes: 3

Views: 78

Answers (2)

Pascal MARTIN
Pascal MARTIN

Reputation: 401142

The debug_zval_dump() function might help you answer this question.


For example, if I run the following portion of code :
$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)
}

I get the following output :

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)

So, I would say :
  • Strings are "refcounted", when passed to functions (and, probably, when assigned to variables)
  • BUT do not forget that PHP does copy on write

For more informations, here are a couple of links that might be useful :

Upvotes: 7

John Giotta
John Giotta

Reputation: 16964

They are copies or dereferenced.

Upvotes: 1

Related Questions