Re: 'switch-expression' and the 'type guard' unary operator demo
| From: | Mike Schinkel | Date: | Mon, 21 Oct 2019 20:18:29 +0000 |
| Subject: | Re: 'switch-expression' and the 'type guard' unary operator demo | ||
| References: | 1 2 3 4 5 6 7 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-107614@lists.php.net to get a copy of this message | ||
> On Oct 21, 2019, at 11:12 AM, Rowan Tommins <rowan.collins@gmail.com> wrote:
>> What if in the future PHP implements variadic syntax for assigning to
>> arrays, e.g. $var = 1,2,3 where $var could satisfy a $variadic parameter
>> set of parameters w/o requiring
...? If PHP embraces that
>> — note GoLang
>> has something similar — then will comma syntax allow for it with hacky use
>> of parentheses?
>> $y = switch ($x) {
>> case 1 => $var = 1,2,3, $var[1],
>> case -1 => $var = 9,8,7, $var[1],
>> default => null,
>> };
>
> I'm not really clear what feature you're suggesting here, but I'm pretty
> sure it conflicts with existing uses of commas, so shouldn't constrain us
> from using them elsewhere.
>
> foo(1,2,3);
> foo($var = 1,2,3);
> $a = [0, $var = 1,2,3];
> // etc
You may well be right.
But to follow up to clarify what I was thinking consider the following (hypothetical) PHP syntax.
Note that the return value has two comma separated values, and the assignment can accept those
multiple values into two comma separated variables in the assignment:
function read_file(string $filepath):string,PHP\Error {
$content = file_get_contents( $filepath );
$error = false === $content
? new PHP\Error( "failed to open '%s'", $filepath )
: null;
return $content, $error;
}
$content, $err = read_file( __DIR__ . '/myfile.txt' );
if (!is_null( $err ) ) {
error_log($err->message);
}
Now yes I know we can do this with arrays and list(), but I have never seen anyone do this in the
wild and hence I think it is not idiomatic PHP. And I hypothesize they do not do this because it is
ugly to read and write and because PHP will throw a runtime error (vs. load-time error) if you have
fewer values returned than you assign:
function read_file( string $filepath ): array {
$content = file_get_contents( $filepath );
$error = false === $content
? new My\Error( "failed to open '%s'", $filepath )
: null;
return array( $content, $error );
}
list( $content, $err ) = read_file( __DIR__ . '/myfile.txt' );
if ( ! is_null( $err ) ) {
error_log( $err->message );
}
With the first example PHP could type check at load time vs. having to wait for coverage of this
code at runtime, and :array type hint in the latter is not as good as the
:string, PHP\Error type hint of the former.
I am probably having unreasonable expectations to believe we will ever see this type of thing in
PHP. Still I hold out hold and want to register an objection if I see new syntax that would make
this syntax impossible in the future. #fwiw
-Mike