0

我有旧代码需要迁移到较新的 PHP 版本。此代码对现在已弃用的create_function. 为了避免手动更新所有内容,我尝试使用rector

我已经使用这个rec​​tor 配置文件来更新所有的create_function用途。

<?php

use Rector\Core\Configuration\Option;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Rector\Php72\Rector\FuncCall\CreateFunctionToAnonymousFunctionRector;

return static function (ContainerConfigurator $containerConfigurator) {
    $parameters = $containerConfigurator->parameters();
    $parameters->set(Option::PATHS, [
        __DIR__ . '/src',
    ]);

    $services = $containerConfigurator->services();
    $services->set(CreateFunctionToAnonymousFunctionRector::class);
};

结果,校长已将部分替换为

function register_skin_deactivation_hook_function($code, $function) {
    $GLOBALS[ 'register_skin_deactivation_hook_function' . $code] = $function;
    $fn=create_function('$skin', ' call_user_func($GLOBALS["register_skin_deactivation_hook_function' . $code . '"]); delete_option("skin_is_activated_' . $code. '");');
    add_action( 'switch_s' , $fn );
}

function register_skin_deactivation_hook_function($code, $function) {
    $GLOBALS[ 'register_skin_deactivation_hook_function' . $code] = $function;
    $fn=function ($skin) use ($GLOBALS, $code) {
            call_user_func($GLOBALS["register_skin_deactivation_hook_function{$code}"]);
            delete_option("skin_is_activated_{$code}");
    };
    add_action( 'switch_s' , $fn );
}

但不幸的是,这会导致错误

致命错误:不能使用自动全局作为词法变量

$fn=function ($skin) use ($GLOBALS, $code) {

我该如何解决这个问题?

4

1 回答 1

0

这是(或曾经是)Rector 转换中的错误:它分析了create_function语句中使用的变量,并构建了use列出所有变量的子句。

但是,由于$GLOBALS是“超级全局”,它在所有范围内都可用,因此不需要(实际上也不能)用use子句捕获。

正确的定义很简单:

function register_skin_deactivation_hook_function($code, $function) {
    $GLOBALS[ 'register_skin_deactivation_hook_function' . $code] = $function;
    $fn=function ($skin) use ($code) {
            call_user_func($GLOBALS["register_skin_deactivation_hook_function{$code}"]);
            delete_option("skin_is_activated_{$code}");
    };
    add_action( 'switch_s' , $fn );
}

(注意:这是基于评论的社区 Wiki 答案,以避免问题显示为“未回答”。)

于 2021-03-10T20:16:45.213 回答