PHP和我自己的函数中的奇怪错误

时间:2011-01-17 20:26:19

标签: php

以下是代码:

function change_case($str, $type) {
    return str'.$type.'($str);
}
change_case('String', 'tolower');

它返回一个解析错误。我做错了什么?

3 个答案:

答案 0 :(得分:6)

要使用变量函数,您需要先构建函数名并将其放在变量中,然后调用它(如果有人传递了无效类型,请使用function_exists()):

function change_case($str, $type) {
    $func = 'str' . $type;

    if (function_exists($func))
        return $func($str);
    else
        return $str;
}

不知道你为什么要为strtolower()strtoupper()编写这样的函数。即使您希望自定义函数同时涵盖lowerupper,也不需要进行变量函数调用。

答案 1 :(得分:2)

为什么要创建一个函数来调用单个内置PHP函数?这看起来完全倒退,永远不值得麻烦。您可以使用内置的PHP函数strtolowerstrtoupper来修复问题。

答案 2 :(得分:0)

你想做的事情应该这样做:

function change_case($str, $type) {
  $function = 'str'.$type;
  if(function_exists($function)){
    return $function($str);
  }
}