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 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图