一个小函数,允许查找所有对对象的引用。 在 3 分钟内编写,可能存在错误(例如,在某些地方将对象作为引用传递?)。
<?php
function find_ref_obj($object, $obj, $path) {
if (in_array($obj,$GLOBALS['__REF_CHECKED'],true))
return false;
$GLOBALS['__REF_CHECKED'][]=$obj;
$r = array();
foreach ((array)$obj as $k => $v) {
if ($v === $object)
$r[] = $path . "->$k";
if (is_object($v)) {
$t = find_ref_obj($object,$v,$path . "->$k");
if ($t!==false)
$r=array_merge($r,$t);
}
else if (is_array($v)) {
$t = find_ref_arr($object,$v,$path . "->$k");
if ($t!==false)
$r=array_merge($r,$t);
}
}
if (empty($r))
return false;
else
return $r;
}
function find_ref_arr($object, $arr, $path) {
if (in_array($arr,$GLOBALS['__REF_CHECKED'],true))
return false;
$GLOBALS['__REF_CHECKED'][]=$arr;
$r = array();
foreach ($arr as $k => $v) {
if ($v === $object)
$r[] = $path . "['$k']";
if (is_object($v)) {
$t = find_ref_obj($object,$v,$path . "['$k']");
if ($t!==false)
$r=array_merge($r,$t);
}
else if (is_array($v)) {
$t = find_ref_arr($object,$v,$path . "['$k']");
if ($t!==false)
$r=array_merge($r,$t);
}
}
if (empty($r))
return false;
else
return $r;
}
function find_references($object) {
$r = array();
$GLOBALS['__REF_CHECKED']=array();
foreach ($GLOBALS as $n => $v)
if ($n!='__REF_CHECKED')
if ($n!='GLOBALS') {
if ($v === $object)
$r[]=$n;
if (is_object($v)) {
$t = find_ref_obj($object,$v,$n);
if ($t!==false)
$r=array_merge($r,$t);
}
else if (is_array($v)) {
$t = find_ref_arr($object,$v,$n);
if ($t!==false)
$r=array_merge($r,$t);
}
}
unset($GLOBALS['__REF_CHECKED']);
return $r;
}
function find_refs($object) {
return implode(', ',find_references($object));
}
?>