Re: Type casting syntax

From: Date: Mon, 12 Jul 2021 17:01:24 +0000
Subject: Re: Type casting syntax
References: 1 2 3 4 5 6  Groups: php.internals 
Request: Send a blank email to internals+get-115412@lists.php.net to get a copy of this message
> On Jul 12, 2021, at 11:00 AM, Larry Garfield <larry@garfieldtech.com> wrote: > x > On Mon, Jul 12, 2021, at 9:54 AM, Max Semenik wrote: > >> I was thinking of something akin to many compiled languages' approach of >> "consider this expression is now of that type, and throw an exception if >> it's not". An example of this approach from Benjamin's proposal of old^ >> >> $service = (EmailService) $diContainer->get('email.service'); >> >> Instead of >> >> /** @var EmailService $service */ >> $service = $diContainer->get('email.service'); >> if (!$service instanceof EmailService) { >> throw new TypeError('Expected instance of EmailService, ...'); >> } > > Hm, that's a different creature. I... would be probably OK with something in that > direction, though I wouldn't work on it myself. I think what you're describing here is > more of a type assertion. "Assert that this variable is of type X, otherwise bail." So, > some kind of non-disableable (or maybe disableable?) shorthand for assert($foo > instanceof Bar). Regarding prior art on type assertion, the syntax Go uses is value.(type) so using a similar approach in PHP might look like this (I'm spitballing by using the double colon as a sigil but it could anything that doesn't conflict with existing usage, whatever those options are): $service = $diContainer->get('email.service')::(EmailService); Additionally in Go a type assertion can return a second value which is boolean telling if the type assertion succeeded. Not having this would effectively moot the benefit to a type assertion if you had to wrap with try{}catch{} in case it failed. $service, $okay = $diContainer->get('email.service')::(EmailService); if (!$ok) { echo 'Not an EmailService.'; } #fwiw -Mike

« previous php.internals (#115412) next »