有人會糾正我,如果我錯了,但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