Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are strings referenced in PHP5?

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

like image 577
pyon Avatar asked Jul 24 '26 01:07

pyon


2 Answers

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 :
  • Reference Counting Basics
  • Do not use PHP references
  • Maitrise de la gestion des variables en PHP (in french)
like image 122
Pascal MARTIN Avatar answered Jul 25 '26 15:07

Pascal MARTIN


They are copies or dereferenced.

like image 21
John Giotta Avatar answered Jul 25 '26 17:07

John Giotta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!