neubert neubert - 5 months ago 9x
PHP Question

prepending a string for a variable function call

PHP supports variable functions. eg. if

$str == 'testfunc';
. I'd like to use this to test a bunch of functions like
. I was thinking I could do something like...

${$prefix . 'funcname'}
doesn't work. That gives this error:

Notice: Undefined variable: funcname

Fatal error: Function name must be a string

I've tried several other variations with no success. I'd prefer to do it all in one line instead of doing
$funcname = $prefix . $functname;

Any ideas?


You've tagged this with PHP 5.6 so the right answer is to use either the two lines (you can actually put them on the same line if you really feel the need) or call_user_func or call_user_func_array.

Like many others questions asking how work around syntax limitations to get things done in one go, the Uniform Variable Syntax RFC fixes things right up in PHP 7 where you can use:

($prefix . 'funcname')();

This RFC is grossly under-appreciated.

Here's the thing, you can actually do what you're trying to do in earlier versions.


Warning: This is disgusting. Use at your own risk of retribution from other programmers.

${${$prefix . 'funcname'} = $prefix . 'funcname'}();

It's absolutely horrid, but it works in all supported versions of PHP (and likely earlier, I didn't bother trying.)

For the sake of explaining it all let's say $prefix = "prefix_";.

First ${$prefix . 'funcname'} creates a variable variable (don't use these) that resolves to $prefix_funcname.


${$prefix . 'funcname'} = $prefix . 'funcname'

is the same as

$prefix_funcname = "prefix_funcname"

And because the value of an assignment expression is the value assigned that outermost ${...} gets the value "prefix_funcname" and gives you again a variable variable resolving to $prefix_funcname which we've already given the value "prefix_funcname".

Leaving you with a variable function call to prefix_funcname().

Please don't do this.