1

这是一个关于 PhpStorm(可能还​​有其他 IDE)中的自动完成行为与 PHP 文档块结合的问题。

我必须在我的应用程序中分组类。首先,各种产品(CarProduct、FoodProduct 等)都有各自的类,它们都继承自 BaseProduct,而个别合同的对应物(CarContract、FoodContract 等)都继承自 BaseContract。

<?php

class BaseContract
{
    /** @var BaseProduct */
    private $product;

    /**
     * @return BaseProduct
     */
    public function getProduct()
    {
        return $this->product;
    }
}

Now I have an instance of CarContract, and I wanna get some CarProduct specific information:

<?php

/* PhpStorm thinks, this is BaseProduct */
$product = $carContract->getProduct();

/* hence, getSpeed() is not available for PhpStorm */
$product->getSpeed();

The autocompletion is not working as I like. There are two workarounds for this, but both are not nice:

  1. Overload getProduct() in the subclass, just with updated @return docblocks
  2. Add /** @var CarProduct $product */ everywhere, where I access the product of a CarContract

Is there a "usual" way to solve something like this, or are my workarounds the only solutions?

4

1 回答 1

1

PhpStorm 并不真正允许/不支持执行以下操作:在其他地方定义相同的命名类,并将其用作覆盖真实类定义的参考。你可以这样做..但IDE会警告“同一类的多个定义”,它可能会引入一些奇怪的行为/意外警告......

这是一张要求此类功能的票:https ://youtrack.jetbrains.com/issue/WI-851 - 观看它(星号/投票/评论)以获取有关任何进展的通知。


您的选择是:您可以在本地(对局部变量)提供正确的类型提示,使用@var- 您已经知道它,这是您首先想到的:

<?php

/** @var \CarProduct $product */
$product = $carContract->getProduct();

$product->getSpeed();

另一种可能的方法:而不是覆盖实际方法..您可以尝试做同样的事情,但使用@methodPHPDoc - 将使用您的代码:

<?php
/**
 * My Car Product class
 * 
 * @method \CarProduct getProduct() Bla-bla optional description
 */
class CarContract extends BaseContract ...
于 2017-03-30T08:44:53.763 回答