1

I usually document my PHP function definitions with a phpDocumentor-style docblock:

/**
 * This is a summary of this function.
 *
 * @since 1.0.0
 *
 * @return int
 */
function my_return_something() {
    return 20;
}

My question is, how should I document an anonymous function? For example:

$length = function() {
    return 20;
};
5
  • 5
    You should document not a function, but a variable instead. It will be callable (or, if you need specific reference that it's anonymous function - the \Closure) Commented Dec 22, 2015 at 13:28
  • I didn't think variables were to be documented with a docblock? Commented Dec 22, 2015 at 13:29
  • If used in same context - normally, you don't have to. PHPStorm, for instance, will be perfectly able to get that your $length is a closure even without it. For variables documentations, see the manual. Normally it's not needed. Commented Dec 22, 2015 at 13:31
  • @AlmaDo This variable isn't a class property though. It's just a normal variable in global scope. Commented Dec 22, 2015 at 13:32
  • @AlmaDo gave you correct answer. If you still want to document argument types/return type for your anonymous functions you are free to document them just like regular functions. This is what PHPStorm does when generates auto docblocks. Everybody will understand that. If you add docblocks generate auto documentation then you shouldn't use anonymous functions. They are anonymous and can't be referred by name. Commented Dec 22, 2015 at 13:56

1 Answer 1

3

You should not document the anonymous function, instead you should document a variable. It will look like:

/** @var \Closure $length */
$length = function() {
    return 20;
};

as tag @var is applicable for regular variables as well. That, however, normally isn't needed: as PHPDoc is intended to be used by IDE and most of IDE-s will be able to get that your variable is a closure right because you have your assignment.

If you will want to pass that variable somewhere - the you may hint in in the accepting method/function as a callable or \Closure explicitly, even without PHPDoc (but you also can use PHPDoc as well)

For details about @var tag, see the documentation. Also note, that the closure type or callback will have nothing to do with the value type which is returned by that callback - it is obvious that you're declaring your callback, not calling it (that being said: I assume "length" isn't a good name for a callback as it cause confusion. Use some action-related name instead, like "lengthGetter" or so)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.