Tim
Tim

Reputation: 5681

PHP Doc generic type declaration

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.

Upvotes: 13

Views: 7017

Answers (3)

David Mann
David Mann

Reputation: 2004

Psalm supports this via

/**
 * @template T of Foo
 */

Ref: https://medium.com/vimeo-engineering-blog/uncovering-php-bugs-with-template-a4ca46eb9aeb

Upvotes: 0

Jim Driscoll
Jim Driscoll

Reputation: 904

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.

Upvotes: 6

Dakusan
Dakusan

Reputation: 6691

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

Upvotes: 2

Related Questions