php - create_function refactor

时间:2018-05-23 18:48:57

标签: php refactoring smf-forum

我正在尝试对下面的代码进行重构(其中有更多代码):

    $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)而不使用完全重构?

1 个答案:

答案 0 :(得分: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 . ';';
},