有人会纠正我,如果我错了,但PHP实际上是在适当的时候检测递归。您的分配只需创建附加周期。这个例子应该是:
$arr = array();
$arr = array(&$arr);
这将导致在
array(1) { [0]=> &array(1) { [0]=> *RECURSION* } }
正如预期的那样。
那么,我有点好奇自己如何检测递归,我开始谷歌。我发现这篇文章http://noteslog.com/post/detecting-recursive-dependencies-in-php-composite-values/与此解决方案:
function hasRecursiveDependency($value)
{
//if PHP detects recursion in a $value, then a printed $value
//will contain at least one match for the pattern /\*RECURSION\*/
$printed = print_r($value, true);
$recursionMetaUser = preg_match_all('@\*RECURSION\*@', $printed, $matches);
if ($recursionMetaUser == 0)
{
return false;
}
//if PHP detects recursion in a $value, then a serialized $value
//will contain matches for the pattern /\*RECURSION\*/ never because
//of metadata of the serialized $value, but only because of user data
$serialized = serialize($value);
$recursionUser = preg_match_all('@\*RECURSION\*@', $serialized, $matches);
//all the matches that are user data instead of metadata of the
//printed $value must be ignored
$result = $recursionMetaUser > $recursionUser;
return $result;
}
lol - eeewwwww。 – leeoniya 2012-01-28 01:39:40
不是你的quesiton的答案,但我已经看到了测试'print_r($ var,true)'的指示递归的字符串的解决方案。这是一样讨厌,因为你可以得到,但工程...看到[这里](http://noteslog.com/post/detecting-recursive-dependencies-in-php-composite-values/)一个体面的妥协。 – Basic 2012-01-28 01:42:20
我已删除/编辑我的评论,以包含一个示例的链接,但我同意,它很臭 – Basic 2012-01-28 01:43:23