动态创建函数名称(动态)-PHP [英] Creating a function name on the fly (dynamically) - PHP

查看:75
本文介绍了动态创建函数名称(动态)-PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我正在使用的代码.

Below is the code that I'm working with.

function my_tab( $tabs ) {

    // the following array will be created dynamically
    $colors = array("red", "white", "blue");

    foreach ($colors as $value) {
        $tabs[$value] = array(
            'name' => $value
        );  

        // start creating functions
        function content_for_[$value]() {
            echo "this is the " .$value. " tab";
        }
        // stop creating functions

        add_action('content_for_'.$value, 'content_for_'.$value);
    }
    return $tabs;

}

如您所见,我有一个动态创建的数组.对于每种 color ,我需要创建一个 function .这些函数绑定在 hook 中,并且函数名称必须 exist 存在.到目前为止,我在过去6个小时中尝试的所有操作都会导致类似以下错误:

As you can see, I have an array that's created dynamically. For each color I need to create a function. These functions are tied into hooks and the function names have to exist. So far, everything I've tried for the past 6 hours results in an error similar to:

"call_user_func_array()期望参数1为有效的回调,找不到函数"content_for_green"或函数名称无效"

"call_user_func_array() expects parameter 1 to be a valid callback, function 'content_for_green' not found or invalid function name"

推荐答案

如果您使用的是PHP> = 5.3,则可以使用

If you're using PHP >= 5.3, you can use anonymous functions, e.g.

add_action( 'content_for_' . $value, function() use ( $value ) {
      echo "this is the " . $value . " tab";
   }
);

使用 use 关键字允许匿名函数从当前作用域中捕获变量(例如您的情况下的 $ value ).

With use keyword are allowing the anonymous function to capture the variables from current scope (e.g. $value in your case).

这篇关于动态创建函数名称(动态)-PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆