How can I use PHP closure function like function() use() on PHP 5.2 version?

前端 未结 3 439
一向
一向 2021-01-27 12:48

How can I use PHP closure function like function() use() on PHP 5.2 version as it has no support for anonymous functions?

Currently my code is something like below

3条回答
  •  失恋的感觉
    2021-01-27 13:39

    I assume you are asking for the 'use' directive due to the early value bindings, right? You could use 'create function' and insert there some static variables with the values you have at the creation time, for example

    $code = '
    
    static $taxonomy_name = "'.$taxonomy_name.'";
    static $plural = "'.$plural.'";
    static $post_type_name = "'.$post_type_name.'";
    static $options = json_decode("'.json_encode($options).'");
    
    $options = array_merge(
        array(
             "hierarchical" => false,
             "label" => $taxonomy_name,
             "singular_label" => $plural,
             "show_ui" => true,
             "query_var" => true,
             "rewrite" => array("slug" => strtolower($taxonomy_name))
        ),
        $options
    );
    
    // name of taxonomy, associated post type, options
    register_taxonomy(strtolower($taxonomy_name), $post_type_name, $options);
                ';
    
    $func = create_function('', $code);
    

提交回复
热议问题