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])',
// 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?
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
);
You can reference the array and use it original values in the closure afterwards. Note that the parameters get initialized at definition not when you call it - so this might work for you:
<?php
$string = 'Welcome Mr MM1, MM2 MM3 to the website';
$parametersArray = array('K', 'A' , 'AD');
$refArray =& $parametersArray;
$line = preg_replace_callback(
'(MM[1-9]{1})',
// anonymous
function () use (&$refArray, $parametersArray) {
# stays the same in every call
# it is a copy after all
print_r($parametersArray);
return array_shift($refArray);
},
$string
);
echo $line;
# Welcome Mr K, A AD to the website
?>
As per the docs (See example #6): You cannot initialize a static variable with an expression:
<?php
function foo(){
static $int = 0; // correct
static $int = 1+2; // wrong (as it is an expression)
static $int = sqrt(121); // wrong (as it is an expression too)
$int++;
echo $int;
}