Visual Studio Code 中的 PHP 格式保存

3

您能否使用Visual Code的Beautify扩展程序在保存时同时格式化PHP代码?如果可以,该如何设置?如果不行,有哪个扩展程序可以实现此功能?

4个回答

3

尝试使用由Ben Mewburn开发的插件PHP Intelephense。正如手册所说:

无损PSR-12兼容文档/范围格式化。也可以格式化组合的HTML / PHP / JS / CSS文件。


2
详细解释了Zain的答案,我正在编写PHP和React代码,并且想要自动格式化两者。
首先安装"PHP Intelephense"扩展以格式化PHP代码,再安装"Prettier"扩展以格式化JS代码。然后打开VS Studio Code设置:
1. 点击右上角的图标以JSON格式进行编辑 2. 删除任何通用的默认格式化程序设置 3. 添加JavaScript和React的格式化程序设置 4. 添加PHP的格式化程序设置 5. 保存 Step-by-step instructions

2
您可以使用vscode-php-formatter扩展程序,该程序可以在需要时(通过按键绑定)或保存时格式化您的PHP代码。
它是这个PHP Coding Standards Fixer的包装器,如您所见,它允许非常灵活的配置,因此您可以根据自己的喜好进行调整。
要添加自定义配置,请创建一个.php_cs文件,并将其添加到参数设置中。
phpformatter.arguments: ["--custom-config=/path/to/file/config.php_cs"]

并创建一个带有您自定义规则的文件:

<?php
$finder = Symfony\Component\Finder\Finder::create()
    ->files()
    ->in(__DIR__)
    ->exclude('vendor')
    ->exclude('resources/views')
    ->exclude('storage')
    ->exclude('public')
    ->notName("*.txt")
    ->ignoreDotFiles(true)
    ->ignoreVCS(true);

$fixers = [
    '-psr0',
    '-php_closing_tag',
    'blankline_after_open_tag',
    // more custom rules
];

return Symfony\CS\Config\Config::create()
    ->level(Symfony\CS\FixerInterface::PSR2_LEVEL)
    ->fixers($fixers)
    ->finder($finder)
    ->setUsingCache(true);

Read more at the source


0

大写的 '[PHP]' 对我不起作用。然而小写的可以。像这样:

"[php]": {
    "editor.defaultFormatter": "bmewburn.vscode-intelephense-client"
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接