【问题标题】:Autocomplete dynamic declared method自动完成动态声明的方法
【发布时间】:2016-09-16 05:17:38
【问题描述】:

如何让我的 IDE 注册此方法正在返回参数的实例?

所以我可以这样做:

Class::models()->getModel('newModel')->newModelMethodHere()?

代码有效,但 PHPStorm 中的自动完成功能无效。

    /**
     * Returns the object of the model
     *
     * @var $this->_models[$model] $model
     * @param string object $model
     * @throws Exception
     * @return object
     */
    public function getModel($model)
    {
        if (array_key_exists($model, $this->_models) && class_exists($model) && is_object($this->_models[$model])
            && $this->_models[$model] instanceof $model) {
            if (is_a($this->_models[$model], $model)) {
                /* @var $this->_models[$model] $model */
                return ($this->_models[$model]);
            }
        }
        throw new Exception('Model ' . (string)$model . ' is not registered correctly.');
    }

【问题讨论】:

标签: php phpstorm


【解决方案1】:

我不得不稍微更改我的代码,但我设法让它工作:

namespace PHPSTORM_META {
    $STATIC_METHOD_TYPES = array(
       \ClassName::getModel('') => [
           "" == "@",
       ],
   );
}

在我的 PHPStorm 项目根目录中的新 .phpstorm.meta.php 文件中。

【讨论】:

    【解决方案2】:

    您应该修复您的评论块。 return 应该明确返回什么对象。

     /**
     * Returns the object of the model
     * ...
     * @return ModelNameClass
     */
    

    【讨论】:

    • 不。该函数可以返回不同的对象。全部取决于 $model 参数
    • 那么您必须定义所有可能的返回对象:* @return ModelNameClass|AnotherNameClass|ThirdClass 或者您的所有类都实现的接口。
    • ` 命名空间 PHPSTORM_META { $STATIC_METHOD_TYPES = array( \ClassName::models()->getModel('') => [ "RoutingUri" instanceof \RoutingUri, "" == "@", ] , ); }` 我读到这应该可行。但是三级法好像不行。
    【解决方案3】:

    getModel() 方法可能会根据提供的参数返回不同类型的对象。虽然这不是一个好的做法,但您可以使用一个简单的技巧让 PhpStorm 帮助您自动完成:将 getModel() 返回的值存储到一个变量中,并使用 @var 注释告诉 PhpStorm 它的类型:

     /** @var newModel $model */
     $model = Class::models()->getModel('newModel');
     // Here PhpStorm will be able to help you with its auto-complete
     $model->newModelMethodHere()?
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 2023-03-06
      • 2016-08-04
      • 2012-12-02
      • 1970-01-01
      • 2012-05-15
      相关资源
      最近更新 更多