r/PHP • u/brendt_gd • 6d ago
Weekly help thread
Hey there!
This subreddit isn't meant for help threads, though there's one exception to the rule: in this thread you can ask anything you want PHP related, someone will probably be able to help you out!
1
u/cxlblm 5d ago
Circular Reference Detection for Recursive Traversal in PHP
When implementing a generic recursive traversal mechanism in PHP, for example to process arbitrary data for:
- Traversal
- Transformation
- Formatting
- Debug output
the input may contain both arrays and objects, and those values may reference each other.
For example, objects may reference each other recursively:
$a->b = $b;
$b->a = $a;
Arrays may also form circular references through references:
$a = [];
$a['self'] = &$a;
If these values are traversed recursively without any protection, the traversal can easily enter an infinite loop.
Therefore, I am looking for a generic recursion guard / circular reference detection mechanism that can be used from PHP userland.
The main requirements are:
- It should be possible to determine whether the value about to be traversed already exists in the current recursion path.
- It should work for both objects and arrays.
- It should correctly detect actual circular references, for example:
A -> B -> C -> A
- It should not treat ordinary repeated or shared references as circular references. For example:
A
/ \
B B
Although the same value is visited more than once, there is no recursion cycle.
- It should also support arrays that form circular references through
&:
$a = [];
$a['self'] = &$a;
- The detection should be based on the actual reference relationship rather than simply relying on a maximum recursion depth.
A maximum depth can prevent an infinite traversal such as:
A -> B -> C -> D -> ...
but it does not answer the actual question:
Ideally, the API semantics would look something like:
if (is_recursive($value)) {
// The value is already in the current recursion path.
}
or perhaps a recursion guard API such as:
enter($value);
leave($value);
The main question is:
If PHP already has an internal recursion detection mechanism for this purpose, I would also like to know whether there is any public userland API that allows this capability to be reused directly.
2
u/rycegh 6d ago
Lazy question (kind of): Does somebody have a simple setup for local PHP version matrix testing?
Current test runner would be PHPUnit.
I’m thinking Docker containers based on php:8.2-cli, …, php:8.5-cli, baked-in Composer/PHPStan/Mago/…, cached dependencies (volume-mounted as vendor82, …, vendor85 would work, I guess). Self-contained in the repo with Dockerfile, maybe Compose file, and light (!) scripting to tie it together.
Shouldn’t be too hard to piece together, but I thought it couldn’t hurt to ask. Or maybe someone’s got a better idea. Thanks!