PHPDoc中的闭包语法 [英] Syntax of Closure in PHPDoc

查看:87
本文介绍了PHPDoc中的闭包语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHPDoc中找不到有关Closure类型的任何文档.所以我的问题是如何定义发送到闭包的参数及其返回值?

I cant find any documentation on the Closure type in PHPDoc. So my question is how do I define the parameter of the parameters sent to the closure and its return value ?

示例:

我如何描述回调"将获得"MyCustomClass",数字和字符串,并返回"MyOtherCustomClass"?

How do i describe that the "callback" will get a "MyCustomClass", a Number and a String, and return a "MyOtherCustomClass" ?

/**
 * @param MyCustomClass $cls
 * @param Closure       $callback this isn't really explaining what this is
 *
 * @return MyOtherCustomClass
 */
function changer($cls, $callback){

  return $callback($cls, 2, "a string");
}

changer($aCustomeClass, function($cls, $int, $string){
   return new MyOtherCustomClass($cls, $int, $string);
})

或者如果可能的话?

推荐答案

@param callable $callback确实是用于该部分的语法.您并没有将参数限制为闭包本身……传递给它的任何可调用都将在该实现中接受. Callable是合法的"PHP类型",因此phpDocumentor接受它为有效类型.

@param callable $callback is indeed the syntax to use for that part. You are not limiting that parameter to being a closure itself... any callable that is passed to it will be accepted in that implementation. Callable is a legal "PHP type", so phpDocumentor accepts it as a valid Type.

在您的示例代码中,实际上没有 假设您的changer()方法返回一个MyOtherCustomClass()的原因,因为这完全是由您稍后在用法.充其量,您可以在 at 注释中表示changer()用法,其中 changer() 的这种特殊用法会返回MyOtherCustomClass,因为这是用法的实现,不是changer()实现本身,而是返回特定类型的对象.

In your example code, there's actually not a reason to presume that your changer() method returns a MyOtherCustomClass(), since that is purely dictated by how you write the closure later in the changer() usage. At best, you'd denote in a comment at the changer() usage that this particular use of changer() returns MyOtherCustomClass, because it is that usage's implementation, not the changer() implementation itself, that returns that specific type of object.

至于记录传递的callable必须接受"的参数,我想您必须在param标记的描述部分中执行此操作.没有语法可以描述这种情况.

As for documenting the arguments that the passed callable is "required" to accept, I suppose you'd have to do that in the description piece of the param tag. There is no syntax to describe such a case.

如果我要以这种方式实现某些东西,我会强加一个所有可调用对象都必须显式返回的接口,因此我可以写为changer()返回该接口.当然,这意味着您的MyOtherCustomClass必须实现该接口,但在我看来,这是接近强制" changer()中的返回类型的唯一方法.

If I were to implement something in this manner, I would impose an interface that the callables must all explicitly return, and thus I could write that changer() returns that interface. Of course, this means that your MyOtherCustomClass must implement that interface, but still, that seems to me to be the only way of coming close to "enforcing" a return type from changer().

这篇关于PHPDoc中的闭包语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆