用匿名函数替换create_function

时间:2018-04-27 08:46:22

标签: php anonymous-function php-7.2 create-function

在发布问题之前,我已经检查了this

这是使用create_function

的代码的一小部分
$lambda_functions[$code_hash] = create_function('$action, &$self, $text', 'if ($action == "encrypt") { '.$encrypt.' } else { '.$decrypt.' }');

尝试使用这种方式

$lambda_functions[$code_hash] = function ( $action, &$self, $text ) use ( $encrypt, $decrypt ) {
                if ($action == "encrypt") {
                    return $encrypt;
                } else {
                    return $decrypt;
                }
            };

但未按预期工作$encrypt$decrypt将包含类似于此内容的代码

$encrypt = $init_encryptBlock . '
           $ciphertext = "";
           $text = $self->_pad($text);
           $plaintext_len = strlen($text);

           $in = $self->encryptIV;

             for ($i = 0; $i < $plaintext_len; $i+= '.$block_size.') {
              $in = substr($text, $i, '.$block_size.') ^ $in;
                        '.$_encryptBlock.'
                        $ciphertext.= $in;
             }

             if ($self->continuousBuffer) {
               $self->encryptIV = $in;
             }

             return $ciphertext;
             ';

create_function工作正常但anonymous功能无法确定我哪里出错?

1 个答案:

答案 0 :(得分:1)

不同之处在于,对于create_function(),您的代码作为字符串提交并解释为代码,但使用匿名函数时,字符串将被解释为字符串,而不是其包含的代码。

您只需从$encrypt$decrypt中的字符串中提取您拥有的代码即可。这看起来像这样:

/*
 * Removed the "use ($encrypt, $decrypt)" part, 
 * because those were the strings that contained the code, 
 * but now the code itself is part of the anonymous function.
 * 
 * Instead, i added "use ($block_size)", because this is a vairable,
 * which is not defined inside of your function, but still used in it.
 * The other code containing variables might include such variables as
 * well, which you need to provide in the use block, too.
 */
$lambda_functions[$code_hash] = function ( $action, &$self, $text ) use ($block_size) {
    if ($action == "encrypt") {
        //Extract $init_encryptBlock here
        $ciphertext = "";
        $text = $self->_pad($text);
        $plaintext_len = strlen($text);

        $in = $self->encryptIV;

        for ($i = 0; $i < $plaintext_len; $i+= $block_size) {
            $in = substr($text, $i, $block_size) ^ $in;
            // Extract $_encryptBlock here
            $ciphertext.= $in;
        }

        if ($self->continuousBuffer) {
            $self->encryptIV = $in;
        }

         return $ciphertext;
    } else {
        //Extract $decrypt here
    }
};

请记住,这不是一个完整的答案。您在代码中找到了许多// Extract $variable here个注释,这些注释代表包含变量的每个代码,代码中包含的代码以及需要提取的代码,其中我从$encrypt中删除代码