简体   繁体   中英

In PHP, can you DEFINE a constant that can be used in function names?

In Drupal, there are many functions that are hook_functionname1, hook_functionname2. When writing a module, you have to replace the text 'hook' with your module name, so Drupal loads your module "my_drupal_module" and runs hooks like "my_drupal_module_functionname1" and "my_drupal_module_functionname2".

Is it possible in PHP to use DEFINE to simply define the word "hook" and set it to a string? If it is possible, then you should be able to copy and paste word-for-word hook_anything and not have to change it. And, if you ever wanted to change the name of your module, you would merely change the single constant, rather than find/replace all the function names.

So can you use DEFINE or some other setting to meta-program in PHP?

You want something like:

$moduleFunctionName = 'hook';

$functionNameOne = $moduleFunctionName . '_functionname1';
$functionNameTwo = $moduleFunctionName . '_functionname2';

$functionNameOne = function($var) {
 // blah
}
..//

Function $functionNameOne is defined through anonymous function. It becames available in php from php 5.3.0

Maybe you want something like this

 <?
    define('PREFIX', 'myprefix');

    //like this time you deside that this will me the second part

    $somevar = '_this_function_name';

    // now we combine prefix and name 
    $function_name = PREFIX . $somevar;

    // now we check if we can run this function
    if(!function_exists($function_name)){
    echo "no function $funcion_name exist";
    }
    else{
    $function_name();
    }

    function myprefix_this_function_name(){
    echo 'running function';
    }
    ?>

this will output

running function

This actually works:

define('FN_NAMESPACE', 'hook_');
${FN_NAMESPACE . 'functionNameOne'} = function($var) {
    echo "Hi, I got $var\n";
};
$hook_functionNameOne('test');

Will output

Hi, I got test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM