KAD KAD - 4 months ago 10
PHP Question

assign array to static function variable php

I have a replace callback method where I am trying to replace multiple string occurrences with array values accordingly.

I have passed the

$parametersArray
to the callback method through the
use
keyword as follows (the regex matches 3 elements):

$string = 'Welcome Mr MM1, MM2 MM3 to the website';
$parametersArray = array('K', 'A' , 'AD');

$line = preg_replace_callback(
'(MM[1-9]{1})',
// anonymous
function () use ($parametersArray) {
static $paramArray = $parametersArray;
return array_shift($paramArray);
},
$string
);


I am getting the below error:


Parse error: syntax error, unexpected '$parametersArray' (T_VARIABLE)


If I set the array to the static variable explicitly, I do not get the error and get the expected behavior.

Is there a problem with assigning the array as variable directly to the statically defined variable within the function?

Answer

You can init static variable like this

$line = preg_replace_callback(
    '(MM[1-9]{1})',
    // anonymous
    function ($matches) use ($parametersArray) {
        static $paramArray;

        if (null === $paramArray) {
            $paramArray = $parametersArray;
        }

        return array_shift($paramArray);
    },
    $string
);
Comments