The Fonz
The Fonz

Reputation: 95

Accessing parent function scope from anonymous function in PHP

I made this awesome plugin for wordpress to easily add references to blog posts using latex-like tags. It works really well, but there's one nasty detail: I'm using global variables, as I need to change a variable in an anonymous function of which I can't change the passed parameters (it's a callback function).

I tried the use syntax and it works but the variable gets copied into the anonymous function.

Here's the code, shortened to give a quick overview of what I want to do:

// Global variables, ugh...
// I don't want to declare $reflist here!
$reflist = array();

// Implementation of reference parsing.
function parse_references( $str ) {

    // Clear array
    $reflist = array();

    // I want to declare $reflist here!

    // Replace all tags
    $newstr = preg_replace_callback( "/{.*}/", 
        function ( $matches ) {

            // Find out the tag number to substitute
            $tag_number = 5;

            // Add to $reflist array
            global $reflist;
            // I don't want to have to use a global here!
            $reflist[] = $tag_number;

            return "[$tag_number]";   


    }, $str );

    return $newstr;
}

So does anyone know how to solve this elegantly?

Upvotes: 0

Views: 65

Answers (1)

Amal Murali
Amal Murali

Reputation: 76636

Pass the variable by reference with the use construct. This way, modifying the value of $reflist inside the anonymous function does have an external effect, meaning the original variable's value changes.

$newstr = preg_replace_callback("/{.*}/", function($matches) use (&$reflist) {
    $tag_number = 5;                            // important  ----^     
    $reflist[] = $tag_number;
    return "[$tag_number]";
}, $a);

Upvotes: 2

Related Questions