gpt4 book ai didi

php/phpDoc - @return $这个类的实例?

转载 作者:IT王子 更新时间:2023-10-29 00:12:47 24 4
gpt4 key购买 nike

如何在我的 phpDoc 中将方法标记为“返回当前类的实例”?

在下面的示例中,我的 IDE (Netbeans) 将看到 setSomething 总是返回一个 foo 对象。

但如果我扩展该对象,则情况并非如此 - 它将返回 $this,在第二个示例中是 bar 对象而不是 foo 对象。

class foo {
protected $_value = null;

/**
* Set something
*
* @param string $value the value
* @return foo
*/
public function setSomething($value) {
$this->_value = $value;
return $this;
}
}

$foo = new foo();
$out = $foo->setSomething();

很好 - setSomething 返回一个 foo - 但在下面的示例中,它返回一个 bar..:

class bar extends foo {
public function someOtherMethod(){}
}

$bar = new bar();
$out = $bar->setSomething();
$out->someOtherMethod(); // <-- Here, Netbeans will think $out
// is a foo, so doesn't see this other
// method in $out's code-completion

...对我来说,解决这个问题会很棒,代码完成是一个巨大的速度提升。

谁有聪明的技巧,或者更好的方法,用 phpDoc 记录这个?

最佳答案

更新:

从 Netbeans 7.4 开始,IDE 支持 @return self、static 和 this ( http://wiki.netbeans.org/NewAndNoteworthyNB74#Editor_2)。

class foo {
protected $_value = null;

/**
* Set something
*
* @param string $value the value
* @return this
*/
public function setSomething($value) {
$this->_value = $value;
return $this;
}
}

class bar extends foo {
public function someOtherMethod(){}
}

上一个答案:

记录迭代器的 current() 方法也有类似的问题。由于迭代器针对许多不同的类进行了扩展,因此与它关联的 @return $class 没有意义。我们之前使用过@satrun77 的选项 2,但我使用过 @method在 Netbeans 中取得了一些成功。

class foo {
protected $_value = null;

/**
* Set something
*
* @param string $value the value
* @return foo
*/
public function setSomething($value) {
$this->_value = $value;
return $this;
}
}

/**
* @method bar setSomething($value)
*/
class bar extends foo {
public function someOtherMethod(){}
}

关于php/phpDoc - @return $这个类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4705768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com