douyinglan2599 2016-05-04 17:04
浏览 53
已采纳

PHPDoc类型提示重叠类型

I have a class called Resource but with a fully qualified name like com.example/objects/Resource

If I write a file

use com.example/objects/Resource;

/**
 * Do something
 * 
 * @param Resource $r 
 */
function myfunc( Resource $r ) {
    $r->something();
}

$x = new Resource();
myfunc($x);

Then everything works fine. Because of my use statement, the PHP typehinting is able to handle the the fact that I've passed a variable of type com.example/objects/Resource even though myfunc is only comparing against Resource

The problem is that PHPStorm is not able to handle this. I'm unable to use autocomplete and I get a warning on myfunc($x) which says Expected Resource, got Resource and a warning within the function which says Method 'something' not found in the class Resource. Obviously PHPStorm is assuming I'm using the builtin resource class and not my own Resource class.

If I change the PHPDoc and the function definition to use the fully qualified name, then the previous warnings go away but I get a minor warning which says Unnecessary fully qualified name. I suppose one solution would be to use the fully qualified name and disable the minor warning, but I'd rather not have to use fully qualified names everywhere. I know it's my own fault for creating a class which has the same name as a built in type, but I'm wondering if there is anyway to make this work? Apart from renaming my Resource class?

  • 写回答

1条回答 默认 最新

  • dqalnwuci494308 2016-05-04 17:23
    关注

    You can either use an alias when importing the class. More information can be found here. Example:

    use com.example\objects\Resource as MyResource;
    
    /**
     * Do something
     * 
     * @param MyResource $r 
     */
    function myfunc( MyResource $r ) {
        $r->something();
    }
    
    $x = new MyResource();
    myfunc($x);
    

    You could also specify the whole namespace and class name instead of just the class name. Example:

    /**
     * Do something
     * 
     * @param com.example\objects\Resource $r 
     */
    function myfunc( com.example\objects\Resource $r ) {
        $r->something();
    }
    
    $x = new com.example\objects\Resource();
    myfunc($x);
    

    If you're in a namespace and using this approach, make sure to use a leading \ on your full class name specifier (e.g. $x = new \com.example\objects\Resource();).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀