Re: Object Type Casting Reloaded
| From: | Sebastian Bergmann | Date: | Tue, 23 Apr 2019 05:07:04 +0000 |
| Subject: | Re: Object Type Casting Reloaded | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-105342@lists.php.net to get a copy of this message | ||
Am 22.04.2019 um 23:47 schrieb Benjamin Morel:
These combine into a third advantage: readability. Today's equivalent of
the above one-liner could be:
/** @var EmailService $service */
$service = $diContainer->get('email.service');
if (! $service instanceof EmailService) {
throw new TypeError('Expected instance of EmailService, ...');
}
Today's equivalent is, at least for me, is this one-liner:
assert($service instanceof EmailService);This way the IDE knows what type $service is supposed to be and there will be an exception at runtime (given the appropriate configuration) when this is not the case. Personally, I prefer hand-written factories that have an explicit createEmailService() method with a :EmailService return type declaration, for example, over the implicitness of a dependency injection container as the latter disguises and obscures dependencies.