(First of all, I'm totally new to this mailing list, so please excuse me if this is not the correct place/way to make this question.)
I was looking at the new generics support in PSR-5 and looks nice, however, unless I'm missing something, it seems that it can only be used to determine the type of the keys/values in collections, which is cool, but generics are so much more powerful than that...
It would be so nice that PHP supported generics itself, so we could declare the class as Optional<T>, and surely that feature will arrive at some point, but in the meanwhile it'd be nice to be able to support that behaviour through dockblocks...
This is a quick example of what I'm thinking of:
/**
* Object representing an optional value of the type specified by <T>.
*
* @generic<T>
*/
class Optional
{
/**
* @var <T>|null
*/
private $value;
/**
* @param <T>|null $value
*/
public function __construct($value = null)
{
$this->value = $value;
}
/**
* Returns the value of type <T> or throws.
*
* @return <T>
* @throws Exception
*/
public function get()
{
if ($this->value === null) {
throw new Exception();
}
return $this->value;
}
}
/**
* Repository for Thing objects.
*/
class ThingRepository
{
/**
* Optionally returns a Thing by name.
*
* @param string $name
* @return Optional<Thing> <-- Here we specify the type of <T>.
*/
public function getThingByName(string $name): Optional
{
$thing = // fetch thing by name, which may not exist...
return new Optional($thing);
}
}
// Now, in any client code, we now get() will return a Thing object!
$thing = $repository->getThingByName('Some thing')->get();
Note that this has more use cases, like custom collection implementations having some `get($key)` method, and others... basically any use case for generics could benefit from this behaviour...
Is there any plans to define such functionality?