0

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?

4
  • The $a variable is undefined. It might be a bug. Commented Apr 28, 2014 at 20:13
  • No it's supposed to turn {sometag} into [5] :) Commented Apr 28, 2014 at 20:14
  • Whats the use of $str parameter? Commented Apr 28, 2014 at 20:20
  • It's the input string on which preg_replace_callback should be called, but I forgot to change it from $a to $str, edited it just now Commented Apr 29, 2014 at 15:26

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.