【问题标题】:syntax error, unexpected T_FUNCTION on "use" operator [duplicate]语法错误,“使用”运算符上的意外 T_FUNCTION [重复]
【发布时间】:2012-08-11 19:28:01
【问题描述】:

可能重复:
How can I use PHP closure function like function() use() on PHP 5.2 version?

我正在尝试在运行 php 5.2 的服务器上运行它。

function add_post_type($name, $args = array() ) {
add_action('init',function() use($name, $args) { 

    // execute custom post type code here

});
};

第二行抛出了一个意外的 T_FUNCTION 错误,我怀疑它的原因是“使用”运算符。有人可以帮我指出如何重写此函数以在 php 5.2 中运行吗?

【问题讨论】:

  • 我猜是因为您没有在function() 之后指定花括号。但实际上你想做什么?
  • @Hafiz 我正在制作一个自定义帖子类型辅助函数,以将我的 functions.php 文件放入我的 wordpress 主题中。使制作 CPT 更快、更方便。不久前从教程中遵循了这一点。至于花括号,它位于“use($name,$args)”之后,因为据我了解,它使变量可用于下面的函数。无论如何,它在我的具有 PHP 5.3 的 MAMP 上运行良好。我的作品有 5.2

标签: php wordpress error-handling


【解决方案1】:

看到这个函数:-

/* 添加帖子类型 */

function wpse54191_plugin_init() {
add_post_type('Netherlands', array(
    'supports' => array('title', 'editor', 'thumbnail', 'comments')
));
}
add_action('init', 'wpse54191_plugin_init');

/* Add Post Type */
function add_post_type($name, $args = array() ) {   
    if ( !isset($name) ) return;

    $name = strtolower(str_replace(' ', '_', $name));
    $args = array_merge(
        array(
            'label' => 'Members ' . ucwords($name) . '',
            'labels' => array('add_new_item' => "Add New $name"),
            'singular_name' => $name,
            'public' => true,
            'supports' => array('title', 'editor', 'comments'),
        ),
        $args
    );

    register_post_type( $name, $args);
}

【讨论】:

  • 棒极了,看起来不错,马上试试
【解决方案2】:

这个答案似乎为您在 PHP 5.2 中尝试做的事情提供了一个很好的解决方案:将匿名函数转换为用户定义的函数。

Converting Code with Anonymous functions to PHP 5.2

祝你好运!并尝试升级您的 PHP 版本:P

【讨论】:

  • 谢谢,看来我得赶上这个话题了。我在一个无法访问 WHM 或 shell 的共享主机包上,所以我不认为我可以自己升级它。
猜你喜欢
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 2010-11-20
  • 2012-05-11
相关资源
最近更新 更多