对于只能接受一个参数(字符串)的函数,例如 trim()、strtolower() 等,您可能可以这样做...?
function modify_str (&$str, $funcName) {
if (function_exists($funcName)) $str = $funcName($str);
}
// So you can now do
modify_str($str, 'trim');
modify_str($str, 'strtolower');
...但老实说,我真的不明白这一点 - 一方面,你不能链接通过引用获取参数的函数(即你不能这样做trim(strtolower($str)))
我倾向于不写$str = trim($str);,因为我可能会立即在其他一些操作中使用结果。而不是这个:
$str = trim($str);
some_func($str, $someOtherVar);
我只是这样做:
some_func(trim($str), $someOtherVar);
如果我需要这样做:
$str = trim($str);
some_func($str, $someOtherVar);
another_func($str, $yetAnotherVar);
我会这样做:
some_func($str = trim($str), $someOtherVar);
another_func($str, $yetAnotherVar);
...但是无论您通过执行上述任何操作来尝试做什么,您正在有效实现的目标是降低您的代码的可读性,并且可能没有别的。
编辑
今天做了一些完全不相关的事情后,我意识到有一种方法可以链接函数并通过引用来调用它:
function modify_str (&$str) {
$args = func_get_args();
for ($i = 1; isset($args[$i]); $i++) {
if (function_exists($funcName = $args[$i])) $str = $funcName($str);
}
}
// So you could do
modify_str($str,'trim','strtolower');
...但我仍然认为这不是要走的路。
另一个编辑
您可以通过执行以下操作(未经测试)传递给使用多个参数的函数:
function modify_str (&$str) {
$str_identifier = '$$$'; // This identifies the argument where $str should be used
$ops = func_get_args();
for ($i = 1; isset($args[$i]); $i++) { // Loop functions to be applied
if (function_exists($ops[$i]['function'])) {
$args = array();
for ($j = 0; isset($ops[$i][$j]); $j++) { // Loop arguments for this function and build an argument list in PHP syntax
$args[] = ($ops[$i][$j] === $str_identifier) ? '$str' : "\$ops[\$i][$j]";
}
// eval() it (as if you had written it as straight PHP)
eval("\$str = {$ops[$i]['function']}(".implode(',',$args).");");
}
}
}
// So you can call it like this
modify_str($str,array('function'=>'str_replace','&','&','$$$'),array('function'=>'explode',"\n",'$$$'));
// ..which should have the same effect as
$str = explode("\n",str_replace('&','&',$str));
// As you can see, the not-by-reference way is is much shorter and more readable