如何在PHP注释@return中使用变量以支持PhpStorm跳转?
getService() Method Hey there! I totally get what you're aiming for—wanting PhpStorm to correctly identify the dynamic model class returned by your getService() method, so you can use Ctrl+Click to jump straight to the right class methods like bar(). The issue with your original @return \Panel\Model\{$Service} syntax is that PHP Doc doesn't support dynamic variable substitution directly in return tags. But don't worry, there are a few solid ways to fix this.
Solution 1: Use Generic Templates (@template)
This is the most flexible approach, as it lets PhpStorm dynamically infer the return type based on the $Service parameter you pass in. Here's how to update your method's docblock:
/** * @template T of string * @param T $Service * @return \Panel\Model\{T} */ public function getService($Service){ // Logic to fetch the service from Model folder }
How it works:
- The
@template T of stringline defines a type parameterTthat represents the string value of your$Serviceargument. - We bind this template to the
$Serviceparameter with@param T $Service. - In the
@returntag,{T}tells PhpStorm to replace it with the actual string passed to$Service(likefoowhen you callgetService('foo')).
Now when you write $this->getService('foo')->bar(), PhpStorm will recognize the return type as \Panel\Model\foo and let you Ctrl+Click bar() to jump to its definition.
Solution 2: Explicit @method Annotations (For Common Services)
If you have a set of frequently used services, you can declare their return types explicitly in your class-level docblock. This is great if you don't need full dynamic support and want precise hints for specific cases:
/** * @method \Panel\Model\foo getService('foo') * @method \Panel\Model\bar getService('bar') */ class YourClass { public function getService($Service){ // Logic to fetch the service from Model folder } }
Each @method line maps a specific $Service value to its corresponding model class. PhpStorm will pick up these declarations and enable Ctrl+Click for those specific calls.
Solution 3: Inline Variable Type Hints (Quick Fixes)
For one-off calls where you just need to enable jumping, you can add an inline docblock to the variable you assign the service to:
/** @var \Panel\Model\foo $fooService */ $fooService = $this->getService('foo'); $fooService->bar(); // Ctrl+Click bar() works here!
This directly tells PhpStorm the type of $fooService, bypassing the need to modify the original getService() method's docblock.
Recommendation
Stick with Solution 1 (@template) if you want full dynamic support—it's the cleanest and most scalable option. The other solutions work well for specific, limited use cases.
内容的提问来源于stack exchange,提问作者SayJeyHi

