简体   繁体   English

PHP-create_function重构

[英]php - create_function refactor

I'm trying to do refactor of some code like below (there is much more of them): 我正在尝试重构某些代码,如下所示(它们更多):

    $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) . '));'),

        // ...
    );

So for entity_fix I have done: 因此,对于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 . ';';
},

but I getting: Undefined variable: num which is logical. 但我得到: Undefined variable: num这是合乎逻辑的。
So, is it possible to refactor this array ( smcFunc ) without full-refactor of usage? 因此,是否可以在不完全使用的情况下重构此数组( smcFunc )?

Try defining the function without the use() language construct. 尝试在不use()语言构造的情况下定义函数。 $num is defined in the function and does not need to be inherited outside the function's scope. $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 . ';';
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM