You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让phpcbf自动修复Generic.PHP.RequireStrictTypes缺失声明并添加严格类型声明?

自动为PHP文件添加严格类型声明的解决方法

问题分析

你启用了Generic.PHP.RequireStrictTypes规则,但运行phpcbf后没有自动添加declare(strict_types = 1);,是因为该规则默认仅做检查,不提供自动修复能力,需要手动开启修复配置。

方法一:调整PHPCS规则配置开启自动修复

修改你的ruleset.xml,为Generic.PHP.RequireStrictTypes规则添加修复配置,指定声明的插入位置(确保在PHP打开标签<?php之后):

<?xml version="1.0"?>
<ruleset name="PrimaryStandard">
    <description>Primary coding standard</description>
    <rule ref="PSR2"/>
    <rule ref="PSR12"/>
    <rule ref="Generic.PHP.RequireStrictTypes">
        <!-- 开启自动修复 -->
        <properties>
            <property name="fixable" value="true"/>
            <!-- 指定声明插入在PHP打开标签之后 -->
            <property name="insertAfterOpeningTag" value="true"/>
        </properties>
    </rule>
</ruleset>

修改完成后,重新运行phpcbf命令:

phpcbf --standard=ruleset.xml /path/to/your/php/files

方法二:用脚本批量添加

如果PHPCS的修复配置不生效,可通过脚本批量处理所有PHP文件:

Shell脚本示例(Linux/macOS)

#!/bin/bash
find /path/to/your/php/files -name "*.php" -type f | while read file; do
    # 检查文件是否已包含strict_types声明
    if ! grep -q "declare(strict_types = 1);" "$file"; then
        # 在<?php之后插入声明
        sed -i '' 's/<?php/<?php\n\ndeclare(strict_types = 1);/' "$file"
    fi
done

PHP脚本示例(跨平台)

<?php
$dir = '/path/to/your/php/files';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

foreach ($iterator as $file) {
    if ($file->getExtension() !== 'php') continue;
    
    $content = file_get_contents($file->getPathname());
    if (strpos($content, 'declare(strict_types = 1);') !== false) continue;
    
    // 在<?php后插入声明
    $newContent = preg_replace('/^<\?php/', '<?php' . PHP_EOL . PHP_EOL . 'declare(strict_types = 1);', $content);
    file_put_contents($file->getPathname(), $newContent);
}

内容的提问来源于stack exchange,提问作者ashdoestech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 14:37:11