0

我想发布一个A可以在本地扩展的类(LocalA)。大多数方法都需要返回$this,以便可以链接调用。我正在寻找一种方法来对A(and LocalA) 中定义的方法的返回值进行类型提示,以表示“它返回与调用该方法的对象相同的类”。

这样 IDE 可以在调用后提供建议的方法。

:self是一种语言可能性,但它不会。这意味着在 中定义的方法之后A,IDE 会将结果视为 anA而不是 a LocalA

<?php
class A {
  function a():self {
    return $this;
  }
}
class B extends A {
  function b():self {
    return $this;
  }
}

$o = new B();
$o->➊
$o->a()->➋ 

在➊ IDE 将列出可能的方法a()b(),但在➋ 它只会列出a()

:static会很好,但无效,在 PHP 中不受支持/实现。

下面的答案看起来很有希望,PHP 很乐意运行它:

trait trait1 {
  function a():self {
    return $this;
  }
}
trait trait2 {
  function b():self {
    return $this;
  }
}

class A {
  use trait1;
}
class B {
  use trait1;
  use trait2;
}

$o = new B();
$o->➊ // offers a() and b() ✔
$o->a()->➋ // offers only a() ✖ treats the trait's 'self' as that trait, I think. 

...但令人讨厌的是,我的语言服务器(通过coc-phpls 进行 intellepense)没有意识到特征中的“自我”应该指代B并因此包含所有这两个特征。

我正在尝试构建一个接收数据的导入器类,做一些事情。我正在使用流畅的界面(很多return $this)。我希望其他第三方能够通过添加他们自己的方法来扩展它,但这整件事实际上是关于开发人员的体验,所以我希望 IDE 能够获取插件提供的方法。

4

1 回答 1

0

我发现以下有效,尽管也对其他答案持开放态度。

<?php
class A {
  /**
   * @return static
   */
  public function a() { return $this; }
}

class LocalA {
  /**
   * @return static
   */
  public function b() { return $this; }
}

$o = new LocalA();
$o->➊ // offers a() and b() ✔
$o->a()->➊ // offers a() and b() ✔
$o->a()->b()->➊ // offers a() and b() ✔

不过,我实际上无法在 PHP 语言中指定这一点,这似乎很遗憾。

于 2021-10-18T17:06:13.937 回答