phpDocumentor / fig-standards

Standards either proposed or approved by the Framework Interop Group
http://www.php-fig.org/
Other
360 stars 85 forks source link

Generics: material type arguments #109

Closed mindplay-dk closed 5 years ago

mindplay-dk commented 9 years ago

This may be a controversial feature, and I'm not even sure it would work well, but it may be necesary - just bear with me and ponder this.

Suppose you have a factory function (as is common in DI containers, controller factories, etc.)

Simplest case, the equivalent of create<T>() : T where T is a the type being created, e.g.:

function create($type) {
    return new $type();
}

$user = create(User::class);

If we could describe the fact that $type is a "material" type argument, e.g. a string with an actual class-name, we could infer the type of $user in this example as User.

Off the top of my head, here's one idea:

/**
 * @template T
 * @param string T=$type
 * @return T
 */
function create($type) {
    return new $type();
}

Here @param string T=$type designates the argument $type as being the material type argument.

It would work, but is it too exotic?

Please feel free to suggest a better approach or a better syntax.

Supported forms of material type-hints could include any constant expression - i.e. the following forms would all be valid:

$user = create('User');                   # string constant
$user = create(User::class);              # magic ::class constant
$user = create(User::CLASS_NAME);         # class constant
$user = create(USER_CLASS);               # global constant
$user = create(UserNamespace\USER_CLASS); # namespaced constant

What do you think?

mindplay-dk commented 5 years ago

Closing this to avoid scope creep for the PSR.