I’m trying to make an associative array with values that are references to functions. What is the proper way to do this? This code works, but gives me a warning.
Code
<?php
$mergeCodes = array(
'rev:(\d+)' => reverse_me,
);
$test = "This is a [[rev:1234]] test";
echo "BEFORE: $test\n";
foreach ($mergeCodes as $code => $callback) {
$code = '\[\[' . $code . '\]\]';
$test = preg_replace_callback( "/$code/", $callback, $test );
}
echo "AFTER: $test\n";
function reverse_me($input) {
return strrev($input[1]);
}
?>
Output
PHP Notice: Use of undefined constant reverse_me - assumed 'reverse_me' in /tmp/test2.php on line 4 BEFORE: This is a [[rev:1234]] test AFTER: This is a 4321 test
As far as I know, PHP does not have such concept. You’re probably confused by JavaScript.
It seems that your final purpose is to make a call to
preg_replace_callback(). As the name suggests you have to feed it with a callback and that’s something pretty simple. All you need is a regular variable that contains one of these:'foo'array('Foo', 'doBar')array($myFoo, 'doBar')Find further reference at https://www.php.net/manual/en/language.types.callable.php