On Wed, Apr 10, 2019 at 12:52 PM Nikita Popov <nikita....@gmail.com> wrote:
>
> I'm a bit concerned that there are two possible semantics for what (?int)
> does:
>
>  1. What I would intuitively expect: A fallible integer cast. I.e. try to
> cast to integer and if not possible return null. So (?int) "foobar" becomes
> null rather than 0.
>  2. What this RFC proposes: A normal integer cast that leaves null alone.
>
> Both behaviors make sense to me generally ... and if there are two ways to
> interpret a piece of syntax, I'd say the syntax is not explicit enough.

The syntax mirrors nullable type declarations, but the thing is
implicit and explicit conversions don't always behave the same today:

```php
<?php
declare(strict_types=0); // weak mode
error_reporting(-1);

$non_numeric_string = "foobar";

var_dump(array_slice([1,2,3], $non_numeric_string, null, true)); //
Warning, then prints `NULL`
var_dump(array_slice([1,2,3], 0, $non_numeric_string, true)); //
prints `array(0) { }`

var_dump(mb_substr("abc", $non_numeric_string, null, "UTF-8")); //
Warning, then prints `NULL`
var_dump(mb_substr("abc", 0, $non_numeric_string, "UTF-8")); //
Warning, then prints `NULL`

var_dump(+$non_numeric_string); // Warning, then prints `int(0)`
// (I can't think of a nullable equivalent for unary +)

(function (int $x) { var_dump($x); })($non_numeric_string); // TypeError
(function (?int $x) { var_dump($x); })($non_numeric_string); // TypeError

var_dump((function ($x): int { return $x; })($non_numeric_string)); // TypeError
var_dump((function ($x): ?int { return $x; })($non_numeric_string));
// TypeError

var_dump((int) $non_numeric_string); // prints `int(0)`
var_dump((?int) $non_numeric_string); // ...what would you expect?
```

-- 
Guilliam Xavier

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to