Re: Renaming "strict types" to "scalar type coercion"

From: Date: Fri, 21 Jun 2024 14:21:55 +0000
Subject: Re: Renaming "strict types" to "scalar type coercion"
References: 1 2 3 4 5 6 7  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
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). 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. Regards, -- Pierre

Thread (28 messages)

« previous php.internals (#123731) next »