Re: Proposal: AS assertions
| From: | Robert Landers | Date: | Thu, 21 Mar 2024 19:03:22 +0000 |
| Subject: | Re: Proposal: AS assertions | ||
| References: | 1 2 3 4 5 6 7 8 9 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-122715@lists.php.net to get a copy of this message | ||
On Thu, Mar 21, 2024 at 7:01 PM Rowan Tommins [IMSoP]
<imsop.php@rwec.co.uk> wrote:
>
> On 21/03/2024 15:02, Robert Landers wrote:
>
> I don't think you are getting what I am saying.
>
> $a as int|float
>
> would be an int, float, or thrown exception.
>
> $a as int|float|null
>
> would be an int, float, or null.
>
>
> I get what you're saying, but I disagree that it's a good idea.
>
> If $a is 'hello', both of those statements should throw exactly the same error, for
> exactly the same reason - the input is not compatible with the type you have specified.
>
>
>
> Another way of thinking about is:
>
> $x = $a as null
>
> What do you expect $x to be?
>
>
> The same as $x inside this function:
>
> function foo(null $x) { var_dump($x); }
> foo($a);
>
> Which is null if $a is null, and a TypeError if $a is anything else:
> https://3v4l.org/5UR5A
>
>
> Regards,
>
> --
> Rowan Tommins
> [IMSoP]
I suppose we are taking this from different viewpoints, yours appears
to be more of a philosophical one, whereas mine is more of a practical
one.
$x = $a as null;
(or any other value, such as true|false) appears to have no practical
purpose in this particular case. This is better checked with
===, or
even in_array(). Values are easy to check in PHP and there are already
lots of great and simple ways to check a value. Further, reading "$x =
$a as null", as a native English speaker, appears to be the same as
"$x = null".
As I mentioned in the beginning, I see this mostly being used when
dealing with mixed types from built-in/library functions, where you
have no idea what the actual type is, but when you write the code, you
have a reasonable expectation of a set of types and you want to throw
if it is unexpected. Right now, the best way to do that is to simply
set a function signature and pass the mixed type to the function to
have the engine do it for you; or write out a bunch of instanceofs
when that isn't worth it. However, this is cumbersome.
I'd also like to say that I'm not strongly attached to the |null
behavior I'm proposing, but there are better ways to assert a variable
is equal to a value. It makes more sense, from a practical programming
point-of-view, to simply return the value given if none of the types
match.
Robert Landers
Software Engineer
Utrecht NL