Dynamic function name in php Dynamic function name in php wordpress wordpress

Dynamic function name in php


Simple enough, here's a similar snipped form a project:

$function = $prefix . '_custom_type_init';if(function_exists($function)) {  $function();}


This is an old thread but simply use anonymous functions:

add_action('init', function() use($args) {    //...});

Then there is no need to declare so many functions.


Edit (2017-04): Anonymous functions (properly implemented) are the way to go, see answer by David Vielhuber.

This answer is ill advised, as is any approach that involves code as a string, because this invites (among other things) concatenation.


Im not sure if it is advisable to use, or if it helps you, but php allows you to create "anonymous" functions :

function generateFunction ($prefix) {    $funcname = create_function(        '/* comma separated args here */',         '/* insert code as string here, using $prefix as you please */'    );    return $funcname;}$func= generateFunction ("news_custom_type_init");$func(); // runs generated function

I am assuming add_action just calls whatever function you passed.

http://php.net/manual/en/function.create-function.php

Note: create_function will not return a function with the name you want, but the contents of the function will be under your control, and the real name of the function is not important.