Syntax of Closure in PHPDoc

后端 未结 2 1518
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 03:03

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 ?

相关标签:
2条回答
  • 2020-12-31 03:12

    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.
    0 讨论(0)
  • 2020-12-31 03:29

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

    0 讨论(0)
提交回复
热议问题