【问题标题】:Phpdoc, how to define a variable for code completion what doesnt actually exists?Phpdoc,如何为代码完成定义一个实际上不存在的变量?
【发布时间】:2017-12-20 22:26:12
【问题描述】:

举个例子:

class Example
{
    private $var;

    public function method()
    {
        $this->   here the IDE will offer the var
    }
}

但是如果我有这个怎么办:

class Example
{
    //private $var;

    public function method()
    {
        $this->   var will no longer be offered
    }
}

所以换句话说,即使没有实际变量,我也希望代码完成工作。那是因为我想使用 __get 方法。很遗憾,我不能使用unset($this->var)

【问题讨论】:

  • @property $varname 在类的文档块中
  • 取决于IDE,在eclipse中可以/*@var $variable class*/

标签: php ide phpdoc


【解决方案1】:

这是使用@property 标签的一个很好的例子。它甚至提到了魔术方法__get__set的例子。

在您的情况下,它可能类似于以下内容:

<?php

class Example
{
    /**
     * @property string $var A variable that can be set and gotten with the magic methods
     */

    public function method()
    {
        $this->var; //here the IDE will offer the var
    }
    
    public function __get($name)
    {
        return $this->$name;
    }
}

?>

另外,请注意以下几点:

魔术方法不能替代 getter 和 setter。它们只允许您处理方法调用或属性访问,否则会导致错误。因此,还有更多与错误处理相关的内容。另请注意,它们比使用正确的 getter 和 setter 或直接方法调用要慢得多。
Gordon on PHP __get and __set magic methods

【讨论】:

    【解决方案2】:

    正因为如此,如果我们将使用受保护的变量,然后将这个变量用于相同的调用以及子类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 2014-06-09
      • 2020-12-27
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      相关资源
      最近更新 更多