简体   繁体   中英

PHPDoc type hinting overlapping types

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?

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 (eg $x = new \\com.example\\objects\\Resource(); ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM