3

I am using Visual Studio Code to code PHP8. I wanted to try the strict types declare(strict_types=1).

When using single types, everything is fine:

function doSomething(int $value): ?float
{
    if ($value === null) return null;
    return round($value, 3);
}

When using union types, the compiler throws errors:

function doSomething(int|string $value): ?float
{
    if ($value === null) return null;
    return round($value, 3);
}

Errors:

'VariableName' expected
')' expected
'{' expected
Unexpected '|'
';'
...

I disabled the PHP language features and I am using the PHP Intelephense v1.8.0 extension.

michaelT
  • 1,533
  • 12
  • 41
  • 1
    `$value` cannot be `null`, because the type of `$value` is `int` or `string` (https://3v4l.org/e2kuH#v8.0.15). That said, the error says that the parser doesn't know PHP8 and union types (https://3v4l.org/v4OJf). – Syscall Feb 08 '22 at 07:05
  • So there is currently no PHP VS code extension what supports / works with PHP8? – michaelT Feb 08 '22 at 07:50
  • See also this [interesting comment](https://stackoverflow.com/questions/65475596/how-to-set-vs-code-extension-intelephense-for-php-8#comment115758080_65475596), and [this one](https://github.com/bmewburn/vscode-intelephense/issues/1566). – Syscall Feb 08 '22 at 08:17
  • You make a lot of emphasis in the error being thrown by compiler but that's shown by your IDEs linter (PHP Intelephense). The actual PHP error is "Fatal error: Uncaught TypeError: round(): Argument #1 ($num) must be of type int|float, string given" ([demo](https://3v4l.org/8Xv8g#v8.1.2)) because [round()](https://php.net/round) doesn't accept strings. – Álvaro González Feb 08 '22 at 18:15
  • Also, have you configured PHP Intelephense to use PHP/8.1 syntax? https://stackoverflow.com/questions/70621681/how-do-i-correct-syntax-highlight-in-vs-code-for-php-8-1-enum-class/70621895#70621895 – Álvaro González Feb 08 '22 at 18:17

0 Answers0