【问题标题】:php - create_function refactorphp - create_function 重构
【发布时间】:2018-11-02 20:41:19
【问题描述】:

我正在尝试重构一些代码,如下所示(还有更多):

    $smcFunc += array(
        'entity_fix' => create_function('$string', '
            $num = substr($string, 0, 1) === \'x\' ? hexdec(substr($string, 1)) : (int) $string;
            return $num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) || $num == 0x202E ? \'\' : \'&#\' . $num . \';\';'),

        'htmlspecialchars' => create_function('$string, $quote_style = ENT_COMPAT, $charset = \'ISO-8859-1\'', '
            global $smcFunc;
            return ' . strtr($ent_check[0], array('&' => '&amp;')) . 'htmlspecialchars($string, $quote_style, ' . ($utf8 ? '\'UTF-8\'' : '$charset') . ')' . $ent_check[1] . ';'),

        'htmltrim' => create_function('$string', '
            global $smcFunc;
            return preg_replace(\'~^(?:[ \t\n\r\x0B\x00' . $space_chars . ']|&nbsp;)+|(?:[ \t\n\r\x0B\x00' . $space_chars . ']|&nbsp;)+$~' . ($utf8 ? 'u' : '') . '\', \'\', ' . implode('$string', $ent_check) . ');'),

        'strlen' => create_function('$string', '
            global $smcFunc;
            return strlen(preg_replace(\'~' . $ent_list . ($utf8 ? '|.~u' : '~') . '\', \'_\', ' . implode('$string', $ent_check) . '));'),

        // ...
    );

所以对于entity_fix我已经完成了:

'entity_fix' => function($string) use ($num) {
    $num = 0 === strpos($string, 'x') ? hexdec(substr($string, 1)) : (int) $string;
    return $num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) || $num == 0x202E
        ? ''
        : '&#' . $num . ';';
},

但我得到: Undefined variable: num 这是合乎逻辑的。
那么,是否可以在不完全重构使用的情况下重构这个数组(smcFunc)?

【问题讨论】:

    标签: php refactoring smf-forum


    【解决方案1】:

    尝试在没有use() 语言结构的情况下定义函数。 $num在函数中定义,不需要在函数作用域外继承。

    'entity_fix' => function($string) {
        $num = 0 === strpos($string, 'x') ? hexdec(substr($string, 1)) : (int) $string;
        return $num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) || $num == 0x202E
            ? ''
            : '&#' . $num . ';';
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多