PHPStorm 重构快捷方式以在 use 语句中提供别名

PHPStorm refactor shortcut to give an alias in use statement

当我尝试 use 导致名称冲突的 class 时,即。我有两个名称相同但名称空间不同的 classes,我尝试同时使用它们 PHPStorm 显示重命名第二个 class 的提示 = 给它一个别名 as

<?php
use MyNamespace\SomeClass;
use MyOtherNamespace\SomeClass as SomeOtherClass;

我希望能够在指针位于 class 上时随时调用此提示,最好是通过键盘快捷键。这可能吗?

您可以使用 PHPStorm 重构功能(光标在 SomeOtherClass,Shift+F6),它允许重命名别名及其用法。

click here to see the screenshot

如果您已经在脚本中使用了 SomeClass 而没有别名,首先您应该设置一个同名的别名:

use MyNamespace\SomeClass as SomeClass;

然后重构这个别名,如上所述。

另一种解决方案:

If you import a conflicting name, like Foo\MyClass and you already have use Bar\MyClass; in your document, you should be faced with the following prompt

+--------------------------------------------+
| Import class                               |
+--------------------------------------------+
| Alias name:                                |
| [________________________________________] |
|                                            |
| [X] Always create alias while class import |
|                                            |
|                          [ OK ] [ Cancel ] |
+--------------------------------------------+

The trick is to check the "Always create alias" checkbox to always be faced with the prompt while importing.

Forgot to mention that you should also uncheck the settings

Settings > Editor > General > Auto Import > [ ] Enable auto-import in file scope

Settings > Editor > General > Auto Import > [ ] Enable auto-import in namespace scope

https://laracasts.com/discuss/channels/general-discussion/phpstorm-importing-namespaces-with-aliases/replies/99388

借助 PhpStorm 2018.3,您可以使用 "Replace with Alias" 功能:https://blog.jetbrains.com/phpstorm/2018/12/new-refactorings-in-phpstorm-2018-3/