简体   繁体   English

在PHP中使用变量作为函数名

[英]Use a variable as a function name in PHP

I'm creating a dynamic function in WordPress that requires I create my function names dynamically. 我在WordPress中创建一个动态函数,需要我动态创建我的函数名。

In this instance, I need to generate a unique function name for this gravityforms code: 在这个例子中,我需要为这个gravityforms代码生成一个唯一的函数名:

add_filter( 'gform_validation_message', 'change_message', 10, 2 );
function change_message( $message, $form ) {
    return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
}

So, I have a variable (which will change from time to time) that I want to use for my function name... 所以,我有一个变量(会不时改变)我想用于我的函数名...

$newitem = 'new_item';

...and tried this... ......试过这个......

add_filter( 'gform_validation_message', $newitem, 10, 2 );
function $newitem( $message, $form ) {
    return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
}

...but obviously that does not work. ......但显然这不起作用。 But I think you get the idea of what I am trying to achieve. 但我认为你了解我想要实现的目标。

Is anything like this even possible? 这样的事情甚至可能吗?

Any help is appreciated. 任何帮助表示赞赏。

$thing = 'some_function';
$$thing = function() {
   echo 'hi';
};
$some_function();

Source - Use a variable to define a PHP function Source - 使用变量定义PHP函数

You can simply pass Anonymous function to add_filter function as parameter: 您可以简单地将Anonymous函数传递给add_filter函数作为参数:

$newitem = function($message, $form) {
    return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
};

add_filter('gform_validation_message', $newitem, 10, 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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