Skip to content

[Bug] Closures cannot capture variables by reference using use (&) #178

@nahime0

Description

@nahime0

Description

Closures cannot capture variables by reference using the use (&$var) syntax.

This is required for many recursive closures and algorithms that need to mutate outer scope variables.

Reproduction

<?php
$g = null;
$g = function ($n) use (&$g) {
    return $n <= 1 ? 1 : $n * $g($n - 1);
};
echo $g(5);   // Expected: 120 (5!)

Expected behavior

The closure should capture $g by reference so the recursive call works.

Actual behavior

Parser error:

error[...]: Expected variable in use() capture list
error[...]: Expected '=' after variable name

Environment

elephc 0.21.8

Possible root cause

The closure parameter / capture parsing logic (likely in src/parser/stmt/params.rs or the closure parsing code in src/parser/expr/) does not recognize the & before a captured variable name in the use() list.

The Closure variant in ExprKind has a captures: Vec<String> field, but the parser never populates reference information.

Additional context

This pattern is the standard way to implement recursive anonymous functions in PHP before static variables or fn recursion.

Stress case: functions/closure_recursive.php

Labels: bug, parser, php-compatibility, closures

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingclosuresClosures and anonymous functionsparserParser / AST constructionphp-compatibilityPHP compatibility / deviation from PHP behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions