Dynamic function name in php

后端 未结 6 1058
悲&欢浪女
悲&欢浪女 2021-01-04 16:16

I would like to simplify the creation of \"Custom Post Types\" in WordPress as it is tedious to go through the same script and change all the custom post type name instances

6条回答
  •  耶瑟儿~
    2021-01-04 17:08

    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.

提交回复
热议问题