【问题标题】:Cannot redeclare two functions无法重新声明两个函数
【发布时间】:2016-01-22 19:49:09
【问题描述】:

如何使用附加的代码解决以下问题?似乎 Wordpress(或某种插件)以某种方式调用了该函数两次。

function my_wpcf7_form_elements($html) {
    function ov3rfly_replace_include_blank($name, $text, &$html) {
        $matches = false;
        preg_match('/<select name="' . $name . '"[^>]*>(.*)<\/select>/iU', $html, $matches);
        if ($matches) {
            $select = str_replace('<option value="">---</option>', '<option value="">' . $text . '</option>', $matches[0]);
            $html = preg_replace('/<select name="' . $name . '"[^>]*>(.*)<\/select>/iU', $select, $html);
        }
    }
    ov3rfly_replace_include_blank('countrylist', 'España', $html);
    return $html;
}
add_filter('wpcf7_form_elements', 'my_wpcf7_form_elements');

致命错误:无法在 /Applications/XAMPP/xamppfiles 中重新声明 ov3rfly_replace_include_blank()(之前在 /Applications/XAMPP/xamppfiles/htdocs/w/wp-content/themes/bulwark_child/functions.php:21 中声明) /htdocs/w/wp-content/themes/bulwark_child/functions.php 第 21 行

【问题讨论】:

  • 简单你不能有两个相同的函数名,除非你重载

标签: php wordpress


【解决方案1】:

不要嵌套函数 - 您当前的代码每次调用外部函数时都声明内部函数,从而导致第二次错误:

function ov3rfly_replace_include_blank($name, $text, &$html) {
    $matches = false;
    preg_match('/<select name="' . $name . '"[^>]*>(.*)<\/select>/iU', $html, $matches);
    if ($matches) {
        $select = str_replace('<option value="">---</option>', '<option value="">' . $text . '</option>', $matches[0]);
        $html = preg_replace('/<select name="' . $name . '"[^>]*>(.*)<\/select>/iU', $select, $html);
    }
}
function my_wpcf7_form_elements($html) {

    ov3rfly_replace_include_blank('countrylist', 'España', $html);
    return $html;
}
add_filter('wpcf7_form_elements', 'my_wpcf7_form_elements');

【讨论】:

  • 它完美无瑕。感谢您的解释和提供的代码。事实上,我不是 PHP 专家,所以我没有考虑嵌套函数的问题。 (我会在 5 分钟内将您的答案添加为已接受)
  • 没问题,很高兴能帮到你
【解决方案2】:

检查此文件是否将函数重新声明为建议的错误消息

/Applications/XAMPP/xamppfiles/htdocs/w/wp-content/themes/bulwark_child/functions.php:21

重命名一个函数,看看它是否有效

写一个单独的函数,嵌套函数中调用多个函数:

function my_wpcf7_form_elements($html) {

ov3rfly_replace_include_blank('countrylist', 'España', $html);
return $html;
}



function ov3rfly_replace_include_blank($name, $text, &$html) {
        $matches = false;
        preg_match('/<select name="' . $name . '"[^>]*>(.*)<\/select>/iU', $html, $matches);
    if ($matches) {
        $select = str_replace('<option value="">---</option>', '<option value="">' . $text . '</option>', $matches[0]);
        $html = preg_replace('/<select name="' . $name . '"[^>]*>(.*)<\/select>/iU', $select, $html);
    }
}
add_filter('wpcf7_form_elements', 'my_wpcf7_form_elements');

【讨论】:

    猜你喜欢
    • 2013-08-07
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2013-10-31
    相关资源
    最近更新 更多