【问题标题】:How to type hint the `$this` property in a trait如何在特征中键入提示“$this”属性
【发布时间】:2021-04-28 22:39:07
【问题描述】:

我有一个在课堂上使用的特质。在那个特性中,我希望能够输入提示它正在使用哪个类。

这个特性很可能只被那个类使用。我只是出于组织目的而将其关注点分开。

class Foo extends Model
{
    use Concerns/HasBar;
}
trait HasBar
{
    public function bar()
    {
        $this->... // Type hint $this to Foo
    }
}

【问题讨论】:

  • 你想要类型提示类 Foo 中的所有方法和属性还是只有 public 就足够了?
  • @greeflas 所有方法和属性都会很棒
  • 那你不能用 PHPDoc 来做,我想。如果在 HasBar::bar() 方法中添加 /* @var Foo $this */ 注释,则可以仅键入类的公共成员的提示。
  • 太糟糕了,但你的建议现在就足够了。请发表您的评论作为答案,以便我将其标记为正确。干杯!

标签: php traits type-hinting phpdoc


【解决方案1】:

您可以在您的HasBar::bar() 方法中使用var tag 来键入提示类的公共成员

trait HasBar
{
    public function bar()
    {
        /* @var Foo $this */
        $this->... // Type hint $this to Foo
    }
}

【讨论】:

    【解决方案2】:

    没有办法限制一个特征只在特定类中使用。

    如果你想以这种方式实现,你可以创建一个子类而不是使用一个 trait。

    【讨论】:

    • 我很清楚这一点。我只想能够输入提示(不限制)$this 属性,就像/** @var \Foo */ public $foo;
    猜你喜欢
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 2018-12-06
    • 1970-01-01
    • 2019-07-23
    • 2018-12-13
    相关资源
    最近更新 更多