Hi,
If you want to check if two variables are referencing each other (i.e. point to the same memory) you can use a function like this:
<?php
function same_type(&$var1, &$var2){
return gettype($var1) === gettype($var2);
}
function is_ref(&$var1, &$var2) {
if(!same_type($var1, $var2)) {
return false;
}
$same = false;
if(is_array($var1)) {
do {
$key = uniqid("is_ref_", true);
} while(array_key_exists($key, $var1));
if(array_key_exists($key, $var2)) {
return false;
}
$data = uniqid("is_ref_data_", true);
$var1[$key] =& $data;
if(array_key_exists($key, $var2)) {
if($var2[$key] === $data) {
$same = true;
}
}
unset($var1[$key]);
} elseif(is_object($var1)) {
if(get_class($var1) !== get_class($var2)) {
return false;
}
$obj1 = array_keys(get_object_vars($var1));
$obj2 = array_keys(get_object_vars($var2));
do {
$key = uniqid("is_ref_", true);
} while(in_array($key, $obj1));
if(in_array($key, $obj2)) {
return false;
}
$data = uniqid("is_ref_data_", true);
$var1->$key =& $data;
if(isset($var2->$key)) {
if($var2[$key] === $data) {
$same = true;
}
}
unset($var1->$key);
} elseif (is_resource($var1)) {
if(get_resource_type($var1) !== get_resource_type($var2)) {
return false;
}
return ((string) $var1) === ((string) $var2);
} else {
if($var1!==$var2) {
return false;
}
do {
$key = uniqid("is_ref_", true);
} while($key === $var1);
$tmp = $var1; $var1 = $key; $same = $var1 === $var2; $var1 = $tmp; }
return $same;
}
?>
Although this implementation is quite complete, it can't handle function references and some other minor stuff ATM.
This function is especially useful if you want to serialize a recursive array by hand.
The usage is something like:
<?php
$a = 5;
$b = 5;
var_dump(is_ref($a, $b)); $a = 5;
$b = $a;
var_dump(is_ref($a, $b)); $a = 5;
$b =& $a;
var_dump(is_ref($a, $b)); echo "---\n";
$a = array();
var_dump(is_ref($a, $a)); $a[] =& $a;
var_dump(is_ref($a, $a[0])); echo "---\n";
$b = array(array());
var_dump(is_ref($b, $b)); var_dump(is_ref($b, $b[0])); echo "---\n";
$b = array();
$b[] = $b;
var_dump(is_ref($b, $b)); var_dump(is_ref($b, $b[0])); var_dump(is_ref($b[0], $b[0][0])); echo "---\n";
var_dump($a);
var_dump($b);
?>
* Please note the internal behaviour of PHP that seems to do the reference assignment BEFORE actually copying the variable!!! Thus you get an array containing a (different) recursive array for the last testcase, instead of an array containing an empty array as you could expect.
BenBE.