On Fri, Jun 21, 2024 at 5:49 PM Pierre <[email protected]> wrote:
>
> Le 21/06/2024 à 15:57, Robert Landers a écrit :
> > On Fri, Jun 21, 2024 at 3:01 PM Pierre <[email protected]> wrote:
> >> Le 21/06/2024 à 14:27, Robert Landers a écrit :
> >>
> >> This is why I wanted to work on "as" part of the pattern matching. It
> >> isn't clear what will happen with the actual pattern matching RFC
> >> (yet), but being able to do:
> >>
> >> some_function_expecting_int($_GET['foo'] as ?int);
> >>
> >> And how about:
> >>
> >> some_function_expecting_int(\intval($_GET['foo']));
> >>
> >> And moreover, I'd write something like this, but:
> >>
> >> function validate_int(mixed $value): int {
> >> if (null === $value || '' === $value) {
> >> return null;
> >> }
> >> if (\is_int($value)) {
> >> return $value;
> >> }
> >> if (\is_string($value) && \ctype_digit($value)) {
> >> return \intval($value);
> >> }
> >> throw new \InvalidArgumentException("What what!");
> >> }
> >>
> >> some_function_expecting_int(validate_int($_GET['foo'] ?? null));
> >>
> >> But the example might be erroneous, I see your point, nevertheless making coercion
> >> explicit doesn't seem really relevant to me, the one point I like in your syntax would be null
> >> handling.
> >>
> >> --
> >>
> >> Pierre
> > Or... you could just turn off strict types instead of reinventing
> > coercion that isn't nearly as well documented as the built-in
> > coercion.
>
> That was one of my points actually.
>
> I don't see the use of a syntax such as $foo as ?int
since all
> existing types of coercion are already possible via the cast syntax
> (please correct me if I'm wrong).
>
> In the previous message proposal, the only neat addition was the null
> handling (that's said, that's a really cool point). But cast syntax
> (int) $foo
is really equivalent to $foo as int
in terme of concision
> (less than 2 chars diff).
Well, $foo as int doesn't exist (yet), so there's no telling what it
will be the same as.
> In almost every case you would need coercion you also need validation,
> and validation is not something that's possible with a neat syntax, at
> least not this one, because validation is a business matter, not really
> a technical one.
That may be true, but isn't always true. Other than how it is
represented in memory, is there any difference between "123", 123, and
123.0? That's what coercion does, it makes it so that the actual
representation doesn't matter. The only thing you really have to worry
about are the edge cases (for which there are many, but that number
has slowly gone down over the years and none of the remaining ones are
truly surprising, IMHO).
And if you are just going to cast a float/string to an int anyway, you
still have edge cases (null, no warning about information loss, etc)
to handle.
> Regards,
>
> --
>
> Pierre