Re: Object Type Casting Reloaded

From: Date: Tue, 23 Apr 2019 05:58:28 +0000
Subject: Re: Object Type Casting Reloaded
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-105343@lists.php.net to get a copy of this message
Hello, Sebastian yes; interface or abstract have been somehow created for that purpose; even if I find people abusing of those constructs; now if your container is generalized and represents dynamic data; for instance like a Message class it could hold dynamic data types; let say: // abstract public offsetGet <https://www.php.net/manual/en/arrayaccess.offsetget.php> ( mixed <https://www.php.net/manual/en/language.pseudo-types.php#language.types.mixed> $offset ) : mixed <https://www.php.net/manual/en/language.pseudo-types.php#language.types.mixed> $service = $diContainer['email.service'] of ?EmailService; // else throw TypeError(this type instead of null or EmailService) On Mon, Apr 22, 2019 at 10:07 PM Sebastian Bergmann <sebastian@php.net> wrote: > 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. > > -- > PHP Internals - PHP Runtime Development Mailing List > To unsubscribe, visit: http://www.php.net/unsub.php > >

« previous php.internals (#105343) next »