Reputation: 3114
I used PhpStorm to auto add the return type in the function below:
/**
* @return \Generator|null
*/
function yieldTest(): ?\Generator
{
yield from [1, 2, 3];
}
My question: Why does it add the null
option alongside \Generator
?
I can't see a way for this to return null so I'm wondering if I'm overlooking something in the way yield
works or if this is a quirk from PhpStorm's side and can safely be ditched?
Update:
To clarify - I am asking why PHPStorm generated the return type as ?\Generator
.
I understand that it then added null
to the php doc @return
tag because on the ?
.
Update 2:
Here is the full code form a test file before generating extra bits:
class yieldTestClass
{
public function yieldTest()
{
yield from [1, 2, 3];
}
}
And here is the code after choosing "Declare the return type" from the context menu on the method name:
class yieldTestClass
{
public function yieldTest(): ?\Generator
{
yield from [1, 2, 3];
}
}
I am not sure if this is a native feature in the IDE or from a plugin but if it is a plugin I am guessing it would be this https://plugins.jetbrains.com/plugin/7622-php-inspections-ea-extended-
Same question either way though.
Upvotes: 5
Views: 889
Reputation: 165088
That inspection and intended fix (the code added) is provided by a Php Inspections (EA Extended) plugin.
Please report to a plugin author: https://github.com/kalessil/phpinspectionsea/issues
Upvotes: 1
Reputation: 32260
The ?
means "the return type declaration is not mandatory and can theroetically be omitted". PHPStorm does not do dynamic analysis if you really return null or not.
As of PHP 7.1.0, return values can be marked as nullable by prefixing the type name with a question mark (?). This signifies that the function returns either the specified type or NULL.
Reference: http://php.net/manual/en/functions.returning-values.php
Consider the code examples:
/**
* @return Generator|null
*/
function yieldTest(): ?\Generator
{
yield from [1, 2, 3];
}
/**
* @return Generator
*/
function yieldTest(): \Generator
{
yield from [1, 2, 3];
}
Upvotes: 2