omtr
omtr

Reputation: 879

PHP and a weird error in my own function

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?

Upvotes: 0

Views: 55

Answers (3)

gen_Eric
gen_Eric

Reputation: 227310

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);
  }
}

Upvotes: 0

BoltClock
BoltClock

Reputation: 724532

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.

Upvotes: 6

Michael Irigoyen
Michael Irigoyen

Reputation: 22957

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.

Upvotes: 2

Related Questions