Unexpected observation: var_dump() of an array is

2019-02-13 17:26发布

问题:

I've just been running some simple debug tests against arrays, and noticed that when I do a var_dump() of an array, the output is flagging any element in the array that is referenced by another variable. As a simple experiment, I ran the following code:

$array = range(1,4);

var_dump($array);
echo '<br />';

foreach($array as &$value) {
}

var_dump($array);
echo '<br />';

$value2 = &$array[1];

var_dump($array);
echo '<br />';

which gives the following output:

array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) } 
array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> ∫(4) } 
array(4) { [0]=> int(1) [1]=> ∫(2) [2]=> int(3) [3]=> ∫(4) } 

Note the ∫ symbol alongside element 3 and subsequently element 1. Note also that those entries don't show the entry's datatype.

Following some experimentation, I don't see this if I var_dump a scalar type, or with objects or resources. If the array contains string data, the symbol is a & (and it does still show the datatype), likewise with float, boolean and object entries.

This is running against PHP 5.2.8

First question: When did this behaviour start, or is it something that I simply haven't noticed before now?

Second question: If referenced elements can be flagged in this way by var_dump(), is there any function in core PHP that will allow me to identify if an array element is referenced by another variable; or that will return the refcount or ref flag from a _zval_struct?

回答1:

Not sure if this answers your question, but you can use

debug_zval_dump($array);

to get the refcount:

array(4) refcount(2){ 
    [0]=> long(1) refcount(1) 
    [1]=> &long(2) refcount(2) 
    [2]=> long(3) refcount(1) 
    [3]=> &long(4) refcount(2) 
} 

Also see this Article by Derick Rethans (PHP Core Dev) about Refcounting.