not_a_generic_user
not_a_generic_user

Reputation: 2178

Using anonymous function in php to change multiple variables in outer function

Here is my anonymous function:

            $step = function() use ($text,$count,$new_text) {                           
            $new_text .= $text[$count];                                             
            $count++;

I'm reading a long text value and scanning for bad characters. If the value of $text[$count] is ok, I want to add it to the new text variable and increase the count by calling $step(). Sure, I could just repeat the two lines over and over in my code, but using an anonymous function seemed so much simpler. The only problem is that it doesn't work. The variables aren't changing in the outer function.

What am I doing wrong. Alternatively, what's a different way to do this if there is one? There has to be a way to abstract a few lines of repeated code throughout a function.

Upvotes: 0

Views: 240

Answers (1)

felipsmartins
felipsmartins

Reputation: 13549

You MUST pass by reference if want a modified version of variable after function is performed, like this:

<?php 

$text = 'Some text';

$anon = function() use (&$text) {
    $text .= ' and more...' ;
};

$anon();

print $text; // returns: Some text and more...

The use statement just inherit variables from the parent scope.

Upvotes: 2

Related Questions