0

Here is the code:

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

It returns a parse error. What am I doing wrong?

1
  • What exactly are you trying to do? PHP variables need to start with $, and . is used for concatenation. Commented Jan 17, 2011 at 20:28

3 Answers 3

6

To use a variable function, you build the function name and put it in a variable first, then call it like so (use function_exists() in case someone passes an invalid type):

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

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

No idea why you'd want to write such a function for strtolower() and strtoupper() though. Even if you wanted a custom function to cover both lower and upper, a variable function call is unnecessary.

Sign up to request clarification or add additional context in comments.

1 Comment

I use that function, because there is no support for cyrillic letters for ucfirst.
2

Why are you creating a function to call a single built-in PHP function? This seems completely backwards and will never, ever be worth the trouble. You can fix your problem by using the built-in PHP functions strtolower or strtoupper.

1 Comment

The practice of calling a native method from within a custom method is legitimate, especially if you plan on providing further customized results from the native functions. Remember, the OP asked how to do something, not whether the example was a good idea or not :)
0

What you want to do should be done like so:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.