Search code examples
phpfunctionoptional-parametersfunction-signature

Uncaught ArgumentCountError on function's nullable type parameter


I am using php 8.0 but for some reason union types and nullable types do not seem to work according to the documentation. ?Type or Type|null should make an argument optional according to the docs (https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.union)

But I get an exception.

8.0.0
PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function test(), 1 passed in /var/www/test/test.php on line 10 and exactly 2 expected in /var/www/test/test.php:4
Stack trace:
#0 /var/www/test/test.php(10): test()
#1 {main}
  thrown in /var/www/test/test.php on line 4

Simple test code

//function test(string $hello, ?string $world) {
function test(string $hello, string|null $world) {
        return $hello . ' ' . ($world ?? 'world');
}

echo phpversion() . PHP_EOL;
// Outputs 8.0.0

echo test('hello') . PHP_EOL;
// Expected output: hello world

echo test('hola','mundo');
// Expected output: hola mundo

What is wrong here?


Solution

  • Using string|null as a type-hint in PHP 8 doesn't mean the argument is optional, just that it's nullable. This means you can pass null as a value (or a string, obviously), but the argument is still required.

    If you want an argument to be optional, you need to provide a default value, as follows:

    function test(string $hello, string|null $world = null) {
        // ...
    }
    

    See https://3v4l.org/gXLDH

    The same was true in earlier versions of PHP, using the ?string syntax; the argument was still required, but null was a valid value.