Re: [PHP-DEV] Type casting syntax

This is only part of a thread. view whole thread
  115416
July 12, 2021 20:28 kjarli@gmail.com (Lynn)
On Mon, Jul 12, 2021 at 10:20 PM Mike Schinkel <mike@newclarity.net> wrote:

> It seems you have just illustrated why in reality we really do not need > type casting/assertions in PHP given its current features, because we > already have what we need. >
That's not an argument I agree with, as it would invalidate the need for short closures, null coalesce, constructor property promotion, etc. Continuing on the previous example: ```php $service = $container->get(SomeService::class); assert($service instanceof SomeService); // could be replaced with $container->get(); // or in case of multiple instances: $container->get('the.service.alias'); // perhaps the service is optional $container->get(); ```
  115417
July 12, 2021 20:36 mike@newclarity.net (Mike Schinkel)
> On Jul 12, 2021, at 4:28 PM, Lynn <kjarli@gmail.com> wrote: > On Mon, Jul 12, 2021 at 10:20 PM Mike Schinkel <mike@newclarity.net <mailto:mike@newclarity.net>> wrote: > It seems you have just illustrated why in reality we really do not need type casting/assertions in PHP given its current features, because we already have what we need. > > That's not an argument I agree with, as it would invalidate the need for short closures, null coalesce, constructor property promotion, etc. > > Continuing on the previous example: > ```php > $service = $container->get(SomeService::class); > assert($service instanceof SomeService); > > // could be replaced with > $container->get();
In your hypothetical view here, what happens when the $container does not have SomeService to provide? Does it throw an Exception? -Mike
  115419
July 12, 2021 21:16 kjarli@gmail.com (Lynn)
On Mon, Jul 12, 2021 at 10:36 PM Mike Schinkel <mike@newclarity.net> wrote:

> > In your hypothetical view here, what happens when the $container does not > have SomeService to provide? Does it throw an Exception? > > Up to the developer that implements it. If the signature would be
`get(?string $id): T;` then I would assume an error should be thrown by PHP, or an Exception by the method, or handled by the developer to always return `T`. `?SomeException` as `T` could let the developer not throw an exception if needed and return `null` instead.