phpclosuresphpdoc

Syntax of Closure in PHPDoc


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 ?

Example:

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);
})

Or if its at all possible?


Solution

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