Syntax of Closure in PHPDoc

烂漫一生 提交于 2019-11-30 08:14:12
ashnazg

@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.

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.

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.

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().

use indirect technique

Your code:

/**
 * @param MyCustomClass  $cls
 * @param MyFancyClosure $callback
 *
 * @return MyOtherCustomClass
 */
function changer($cls, $callback){
    return $callback($cls, 2, "a string");
}

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

and than provide a dummy code somewhere:

/**
 * this is awesome closure!
 */
class MyFancyClosure {
    /**
     * @param MyCustomClass $cls
     * @param int           $int
     * @param string        $str
     *
     * @return MyOtherCustomClass
     */
    public function __invoke($cls, $int, $str) {}
}

note:

  1. The function body of __invoke is not required, so leave it blank.
  2. Use "Closure" sufix for class name to clarify it.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!