0

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

该示例有效,但会产生通知。当规则在与定义数组的文件不同的文件中评估时,它将不起作用。我怎样才能解决这个问题?

代码

<?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 保持兼容。

4

3 回答 3

2

Unfortunately, functions are not first class in PHP and you cannot reference them by the symbol name. Instead, your code is trying to reference undefined constants (hence the notices). You can call a function name by string with call_user_func

" a " => "trim"
/* snip */
echo "key:'$key' value:'" . call_user_func($func, $key) . "'\n";
于 2013-10-09T12:44:42.790 回答
2

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

$a = array(
" a " => "trim",
" b " => "noop",
" c " => "trimAndUpper",
);
于 2013-10-09T12:38:48.913 回答
1

你的代码:

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

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

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

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

数组定义也有问题:

" a " => trim,

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

" a " => "trim",
于 2013-10-09T12:38:23.180 回答