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:
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
whereT
is a the type being created, e.g.: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 asUser
.Off the top of my head, here's one idea:
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:
What do you think?