PhpStorm是否可以推断此方法的返回类型?
我想我可能需要在某个地方添加一个特殊的注释,但我希望PhpStorm足够聪明,能够解决给定笨拙继承模式的返回类型 例如,我有一些类似的代码:PhpStorm是否可以推断此方法的返回类型?,phpstorm,phpdoc,Phpstorm,Phpdoc,我想我可能需要在某个地方添加一个特殊的注释,但我希望PhpStorm足够聪明,能够解决给定笨拙继承模式的返回类型 例如,我有一些类似的代码: <?php class Collection extends \ArrayObject { public function __construct(array $items) { foreach ($items as $key => $value) { if (isset(static:
<?php
class Collection extends \ArrayObject
{
public function __construct(array $items)
{
foreach ($items as $key => $value) {
if (isset(static::$requiredType) && !$item instanceof static::$requiredType)
$this->offsetSet($key, $value);
}
}
public function getFirst()
{
return $this->offsetGet(0);
}
}
class MessageCollection extends Collection
{
protected static $requiredType = 'Message';
}
class UserCollection extends Collection
{
protected static $requiredType = 'User';
}
但我想,当我添加更多的集合类时,这会变得有点可笑,甚至毫无用处。试试以下方法:
/**
* @method \User getFirst()
*/
class UserCollection extends Collection
{
protected static $requiredType = 'User';
}
我喜欢这个想法。类似的注释是否也可以用于
foreach
循环?您可以对foreach使用类似的注释:/**var\User[]$items*/
。我不知道每次编写foreach循环时,在代码中乱扔这样的注释会有什么感觉……您可以为方法定义返回类型,该方法返回foreach的集合。类似这样的事情:@return\User[]
。如果你能用foreach做个例子,也许我可以给你一些建议。啊!我明白了。如果使用类注释@method User offsetGet($offset)
,则foreach($userCollection作为$User)
将推断出$User
的正确类型。
/**
* @method \User getFirst()
*/
class UserCollection extends Collection
{
protected static $requiredType = 'User';
}