websealevel
websealevel

Reputation: 101

How two arrays share zval containers in PHP?

I'm studying the basics of memory managment in PHP, and I find it really interesting. Unfortunately the internals of memory managment seems to have change according to PHP versions so I don't always understand the results returned by xdebug_debug_zval, compared to different ressources that explains what results we should expect. That's ok because I'm interested mainly in the broad picture but it prevents me to run tests to test my knowledge.

The question I want to adress is simple :

$a=array(1,2);
$b=$a;
$b[0]='foo';
$b[]='bar';

After affectation $b=$a, a and b symbols point both to the same zval (refcount=2). So far so good. But after $b[0]='foo'; instruction, do a and b still points to the same zval they have in common? How is handled the modification?

In the same idea, after $b[]='bar'; do a and b still point to the same zval with a new node being created (i.e a new zval is created to store 'bar' pointed by 3, the key added to $b) ?

Running xdebug_debug_zval('a') and xdebug_debug_zval('b') gives me respectively

a: (refcount=2, is_ref=0)=array (0 => (refcount=0, is_ref=0)=1, 1 => (refcount=0, is_ref=0)=2, 2 => (refcount=0, is_ref=0)=3)
b: (refcount=1, is_ref=0)=array (0 => (interned, is_ref=0)='foo', 1 => (refcount=0, is_ref=0)=2, 2 => (refcount=0, is_ref=0)=3, 3 => (interned, is_ref=0)='bar')

I am not sure how to interpret it and if that answers my question. I can see that a and b do point to the same zval array, but that's it. How are handled the differences?

So my question is does PHP handles memory like trees, by sharing nodes(zval) pointed by the symbols a and b and by adding nodes(zval) to accomodate the differences between them ?

Thank you very much for any answer, Im sorry the title of my question is not very well formulated

Upvotes: 2

Views: 122

Answers (1)

Jack33232
Jack33232

Reputation: 21

I think this blog can help. https://blog.larapulse.com/php/variables-under-the-hood

Now, if you change the value of one of these variables, PHP seeing the refcount greater than 1, will copy this zval, make the changes there, and your variable will point already to the new zval.

Upvotes: 2

Related Questions