in_array on objects with circular references

余生颓废 提交于 2019-11-30 17:44:59

Turns out the answer is extraordinarally simple. It would appear that by default in_array does non-strict comparison (equivalent to an == operation) when testing the haystack for the needle. This means that it checks that all the properties are equal, which means it starts traversing the object graph, and that can get you into trouble if you have circular references in that graph.

The in_array function has a strict mode, however, which as far as I can tell does the equivalent of an === operation. This seems to cause it to check the references to see if they point at the same object instead of comparing all the properties.

Simply changing the code to:

if (!in_array ($field, $this -> fields, true))

makes the method behave as I wanted it to behave without it triggering the recursion error.

I have to say that I'm a little surprised that PHP doesn't do this mode by default. On the other hand I guess I really ought not to be surprised that PHP's weak typing has caused me an issue again. :)

goat

I would just use either SplObjectStorage or spl_object_hash.

And you're right, when php compares things it traverses the structures recursively (arrays too).

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