Test if variable contains circular references

∥☆過路亽.° 提交于 2020-01-02 03:23:04

问题


How do you test a variable for circular references?

I am using PHP's var_export() function with the return string argument set to true.

I found that Warning: var_export does not handle circular references and was wondering if anyone knew of a way to test if a variable contains a circular reference so that I may use it before trying to use var_export on it.

I know that var_export outputs PHP eval-able text that can be used to recreate the array and even though I am not using it for that I still want to use this function when it is available because the output format meets my needs. var_dump is not an option because it doesn't accept an argument to return a string instead. I am aware that I could buffer the output of var_dump which handles circular references gracefully and save the buffer contents to a variable but I really just want to know if someone knows of a way to test for such references in a variable.

If you want to create a quick circular reference do this:

$r = array();
$r[] = &$r;
var_export($r, true);

回答1:


Hacky but returns true based on the circular example you gave:

<?php
// create the circular reference
$r = array();
$r[] = &$r;

function isRecursive($array){
  $dump = print_r($array, true);
  if(strpos($dump, '*RECURSION*') !== false)
      return true;
  else
      return false;
}

echo isRecursive($r); // returns 1

Interested to see what else people come up with :)




回答2:


Would this do it?

function isRecursive($array) {
    foreach($array as $v) {
        if($v === $array) {
            return true;
        }
    }
    return false;
}


来源:https://stackoverflow.com/questions/17181375/test-if-variable-contains-circular-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!