【问题标题】:Is it possible to type hint $this in traits?是否可以在特征中输入提示 $this?
【发布时间】:2020-08-16 18:49:11
【问题描述】:

我有一个特征,想输入提示 $this 来告知编译器它的类型:

trait MyTrait {
  public function myAwesomeFunction() {
    return new OtherClass($this); // warning: Expected MyAwesomeInterface, got MyTrait
  }
}

class OtherClass {
  public function __construct(MyAwesomeInterface $foo) { ... }
}

所以我想知道是否有类似的东西,例如:

trait MyTrait {
  public function myAwesomeFunction() {
    /**
     *  @var $this MyAwesomeInterface
     */
    return new OtherClass($this); // no warnings
  }
}

这将允许我通知编译器该特征的用户实现了我的接口。

请注意,特征不能在 PHP 中实现接口(请参阅Why PHP Trait can't implement interfaces?)。

感谢您的帮助 ;-)

【问题讨论】:

    标签: php type-hinting phpdoc


    【解决方案1】:

    没有警告,因为您作弊 IDE 参数已正确传递。实际上,运行时总是抛出错误。

    Trait 是为 PHP 中的任何类注入的大量相关函数。它的目的是不用于 OOP。我认为这将有助于实用程序支持功能。

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 2016-02-23
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2021-08-13
      • 1970-01-01
      • 2013-02-05
      相关资源
      最近更新 更多