Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Rediska's avatar

How to convert a string to a function?

I have a question about php)

I have a function. Let's say this:

function getColor ($color) {
	if ($color == '#ff0000') {
		return 'red';
	} else {
		return null;
	}
}

I get a string that should actually be processed like a function.

$str = "getColor(#ff0000)";

How to indicate that this is not a string, but that you need to run the getGender function and pass the '#ff0000' parameter there

0 likes
3 replies
newbie360's avatar

@rediska If i understand the question correctly

$function = 'getColor';

$color = is_callable($function)
    ? $function('#ff0000')
    : null;
1 like
realrandyallen's avatar

Not sure if there's a better way to handle this, but if you don't have the hex code separately you'll need to separate out the function and the color:

$str = "getColor(#ff0000)";

preg_match('/([\w\_\d]+)\(([\w\W]*)\)/', $str, $functionWithParameter)

dd($functionWithParameter);

array:3 [▼ // routes/web.php:31
  0 => "getColor(#ff0000)"
  1 => "getColor"
  2 => "#ff0000"
]

With this you can use call_user_func to call the function and get the matching color for the given hex code:

$color = call_user_func($functionWithParameter[1], $functionWithParameter[2])

Also, your getColor function looks like a good candidate for the match function if you're on PHP version 8+

function getColor ($color) {
   return match ($color) {
      '#ff0000' => 'red',
      '#ffffff' => 'white',
      '#000000' => 'black'
   }
};

1 like
Rediska's avatar

It seems true, but not exactly))) At least it works.

$arrayFunction = explode('(', $str);
$nameFunction = $arrayFunction[0];
$valuesFunction = explode(', ', substr($arrayFunction[1], 0, -1));
$result = call_user_func($nameFunction, ...$valuesFunction);

Please or to participate in this conversation.