Test if variable contains circular references

2019-04-26 20:18发布

问题:

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;
}