Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Doc generic type declaration

Tags:

php

phpdoc

I'm working on a library which uses the phpDocumentor specification on determining the type system using reflection. However, I couldn't find any information about generic type declarations.

Is there any way a generic type declaration should be specified?

For example: is there any specification (in-progress) which specifies anything like:

/**
 * @template <T extends Base>
 */
class Collection {

    /**
     * @return Iterator<T>
     */
    function get_iterator();

}

Note that the code above is just an example to illustrate what I mean by generic type declarations. I do not want this achieve anything to do with collections and iterators.

like image 796
Tim Avatar asked Sep 17 '15 10:09

Tim


2 Answers

There apparently was some interest in the related topic of object specialization because that was added to PSR-5:

generic = collection-type "<" [type-expression "," *SP] type-expression ">"

Edit: and then removed as Jack notes below, albeit with a stated expectation that they'll return in one form or another before it's standardised

However, it doesn't provide a means to define a class as generic, and PSR-5 has been abandoned for a long while. The de-facto standard, phpDocumentor, does not in any way define support for such syntax.

If you want to informally mark up generics, you're best off making up your own syntax (inspired by similar syntax that already exists like Closure's documentation or JSDoc) while carefully avoiding anything that could actively confuse phpDocumentor, something like:

/**
 * @template {Base} T
 */
/**
 * @return Iterator {Iterator<T>}
 */

If you want to do it formally, you'll need to switch to another documentation system like doxygen.

like image 102
Jim Driscoll Avatar answered Oct 18 '22 09:10

Jim Driscoll


You might want to check out the psalm project.

https://psalm.dev/docs/

https://github.com/vimeo/psalm

It supports generics in the documentation, as well as so much more. It's also used by Symfony's DB ORM, doctrine.

It supports Emacs, Phpstorm/Intellij, vim, and visual studio

like image 22
Dakusan Avatar answered Oct 18 '22 09:10

Dakusan