在 PHP 中管理函数数组


manage array of functions in php

我想管理关联数组中的一组文本转换。

该示例有效,但会产生通知。当规则在不同的文件中进行评估时,它不起作用,而不是在定义数组的文件中。如何解决此问题?

法典

<?php
function noop($x){
    return $x;
}
function trimAndUpper($x){
    return strtoupper(trim($x));
}
$a = array(
    " a " => trim,
    " b " => noop,
    " c " => trimAndUpper,
);
foreach($a as $key=>$func){
    echo "key:'$key' value:'{$func($key)}''n";
}

输出

❯❯❯ php ./experiment.php
PHP Notice:  Use of undefined constant trim - assumed 'trim' in /tback/src/experiment.php on line 12
Notice: Use of undefined constant trim - assumed 'trim' in /tback/src/experiment.php on line 12
PHP Notice:  Use of undefined constant noop - assumed 'noop' in /tback/src/experiment.php on line 13
Notice: Use of undefined constant noop - assumed 'noop' in /tback/src/experiment.php on line 13
PHP Notice:  Use of undefined constant trimAndUpper - assumed 'trimAndUpper' in /tback/src/experiment.php on line 14
Notice: Use of undefined constant trimAndUpper - assumed 'trimAndUpper' in /tback/src/experiment.php on line 14
key:' a ' value:'a'
key:' b ' value:' b '
key:' c ' value:'C'

php版本是PHP 5.3.27,我现在必须保持与5.3兼容。

只需引用这些单词,因为您的示例中没有函数数组,而是函数名称(字符串(。

$a = array(
" a " => "trim",
" b " => "noop",
" c " => "trimAndUpper",
);

不幸的是,函数在 PHP 中不是第一类,你不能通过符号名称引用它们。 相反,您的代码正在尝试引用未定义的常量(因此需要注意(。 您可以使用字符串调用函数名称call_user_func

" a " => "trim"
/* snip */
echo "key:'$key' value:'" . call_user_func($func, $key) . "''n";

您的代码:

echo "key:'$key' value:'{$func($key)}''n";

这里的问题是函数调用在带引号的字符串内。尽管可以像这样引用变量,但不能从字符串内部调用函数。

解决方案:从字符串中取出函数调用:

echo "key:'$key' value:'".$func($key)."''n";

数组定义也有问题:

" a " => trim,

这里的函数名称(例如trim(不能像这样简单地用它们的名字来引用;你需要将它们声明为字符串。

" a " => "trim",